问题描述
注意:我使用的是Scala 2.8,这可能是个问题吗?
NOTE: I am on Scala 2.8—can that be a problem?
为什么不能使用与foldLeft
或foldRight
相同的方式使用fold
函数?
Why can't I use the fold
function the same way as foldLeft
or foldRight
?
在设置scaladoc 中表示:
但是我在函数签名中没有看到类型参数T
:
But I see no type parameter T
in the function signature:
def fold [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1
foldLeft-Right
和fold
有什么区别,如何使用后者?
What is the difference between the foldLeft-Right
and fold
, and how do I use the latter?
例如,我将如何编写折叠以将所有元素添加到列表中?对于foldLeft
,它将是:
For example how would I write a fold to add all elements in a list? With foldLeft
it would be:
val foo = List(1, 2, 3)
foo.foldLeft(0)(_ + _)
// now try fold:
foo.fold(0)(_ + _)
>:7: error: value fold is not a member of List[Int]
foo.fold(0)(_ + _)
^
推荐答案
您认为Scala的旧版本存在问题是正确的.如果您查看 scaladoc页面对于Scala 2.8.1,您不会在其中看到任何折叠定义(这与您的错误消息一致).显然,fold
是在Scala 2.9中引入的.
You're right about the old version of Scala being a problem. If you look at the scaladoc page for Scala 2.8.1, you'll see no fold defined there (which is consistent with your error message). Apparently, fold
was introduced in Scala 2.9.
这篇关于fold和foldLeft或foldRight之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!