GA1
GA1

Reputation: 1627

Operator precedence for sum and division on list in Scala

My example uses sum function but this is not the only higher order function I've been having problems with.

To the point

It's been a while but I keep catching myself on writing code like:

scala> List(2, 5, 7, 11) sum / 3

which gives me:

<console>:1: error: ';' expected but integer literal found.

When I add parentheses:

(List(2, 5, 7, 11) sum) / 3

I get what I expect though:

res3: Int = 8
  1. So here is my question. Why does the operator precedence work like this? Why doesn't it infer the parentheses?

  2. Is there any counter-example that could show that such inferring would lead to a fundamentally wrong results in scala?

  3. Why does using .change anything. Why does l.sum / 13 work?

Upvotes: 0

Views: 182

Answers (2)

Jasper-M
Jasper-M

Reputation: 15086

To answer your third question:

Why does using . change anything. Why does l.sum / 13 work?

Let's take a more generic piece of code:

a b c d

How should Scala interpret this? a.b.c.d? a.b(c).d? a.b.c(d)? The fact is that Scala will always interpret this as a.b(c).d even if it doesn't typecheck correctly. Why does it do that? Because if Scala would decide to interpret a b c d differently based on the context of the program, it would be very difficult for readers of programs to understand the meaning of the code they are reading.

So if a.b.c(d) is what you want, you have to write a.b c d so the code can be interpreted unambiguously.

Upvotes: 2

marstran
marstran

Reputation: 28056

Operator precedence in Scala is defined by a set of rules. You can find it here: http://docs.scala-lang.org/tutorials/tour/operators.html

As you can see, alphanumeric letters (such as in sum) has the lowest precedence. However, this only applies if you write the function in infix-form (without dots).

Writing the expression like this will solve your problem:

List(2, 5, 7, 11).sum / 3

Personally, I never call postfix functions without the dot. The Scala compiler even gives you a warning when you write it without the / 3 part:

scala> List(1,2,3,4) sum
<console>:12: warning: postfix operator sum should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scaladoc for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
   List(1,2,3,4) sum

Upvotes: 2

Related Questions