问题描述
任何人都可以解释为什么我忽略用于应用 foldLeft
函数的点符号(版本2.9.2)时为什么会看到以下编译错误
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
不适用于其他高阶函数,如 map
,它似乎并不关心我是否提供点。
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.
我不认为它是一个关联事物,因为我不能只调用 foldLeft(1)
I don't think its an associativity thing because I can't just invoke foldLeft(1)
推荐答案
这是因为foldLeft是咖喱。除了使用点符号,还可以通过添加圆括号来解决此问题:
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
并且关于您对无法调用 foldLeft(l)
的评论,您可以,但您需要像这样部分应用它:
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>
这篇关于为什么在foldLeft中留下点会导致编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!