本文介绍了为什么在 foldLeft 中留下点会导致编译错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我省略应用 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)(_ * _)
                                    ^

但是

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 中留下点会导致编译错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 07:36