Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

scala - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...