fold 和 foldLeft 或 foldRight 之间的区别? [英] Difference between fold and foldLeft or foldRight?

查看:49
本文介绍了fold 和 foldLeft 或 foldRight 之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我使用的是 Scala 2.8——这会不会有问题?

NOTE: I am on Scala 2.8—can that be a problem?

为什么我不能像使用 foldLeftfoldRight 一样使用 fold 函数?

Why can't I use the fold function the same way as foldLeft or foldRight?

Set scaladoc 中,它说:

折叠的结果可能只是这个并行集合的类型参数T的超类型.

The result of folding may only be a supertype of this parallel collection's type parameter T.

但是我在函数签名中没有看到类型参数T:

But I see no type parameter T in the function signature:

def fold [A1 >: A] (z: A1)(op: (A1, A1) ⇒ A1): A1

foldLeft-Rightfold 有什么区别,后者如何使用?

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 之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆