Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does leaving the dot out in foldLeft cause a compilation error?

Can anyone explain why I see this compile error for the following when I omit the dot notation for applying the foldLeft function?(version 2.9.2)

scala> val l = List(1, 2, 3)
res19: List[Int] = List(1 ,2 ,3)

scala> l foldLeft(1)(_ * _)
<console>:9: error: Int(1) does not take parameters
                    l foldLeft(1)(_ * _)
                                    ^

but

scala> l.foldLeft(1)(_ * _) 
res27: Int = 6

This doesn't hold true for other higher order functions such as map which doesn't seem to care whether I supply the dot or not.

I don't think its an associativity thing because I can't just invoke foldLeft(1)

like image 773
nsfyn55 Avatar asked Oct 15 '12 22:10

nsfyn55


2 Answers

It's because foldLeft is curried. As well as using the dot notation, you can also fix this by adding parentheses:

scala> (l foldLeft 1)(_ * _)
res3: Int = 6

Oh - and regarding your comment about not being able to invoke foldLeft(l), you can, but you need to partially apply it like this:

scala> (l foldLeft 1) _
res3: ((Int, Int) => Int) => Int = <function1>
like image 168
Paul Butcher Avatar answered Nov 14 '22 21:11

Paul Butcher


Omitting the dot is possible because of scala's syntactic support for the infix notation, which expects 3 parts:

leftOperand operator rightOperand. 

But because foldLeft had two list of parameters, you end up with 4 parts at the syntactic level: l foldLeft (1) (_ * _)

Which does not fit infix notation, hence the error.

like image 38
Régis Jean-Gilles Avatar answered Nov 14 '22 23:11

Régis Jean-Gilles