gpt4 book ai didi

scala - Fold 和 FoldLeft 方法区别

转载 作者:行者123 更新时间:2023-12-03 05:52:58 25 4
gpt4 key购买 nike

我不确定 Scala 中的 foldfoldLeft 之间有什么区别。

问题Difference between fold and foldLeft or foldRight?有一个关于订购的答案。这是可以理解的。但我仍然不明白为什么这有效(来自 REPL):

scala> Array("1","2","3").foldLeft(0)(_ + _.toInt)
res6: Int = 6

但这并不:

scala> Array("1","2","3").fold(0)(_ + _.toInt)
<console>:8: error: value toInt is not a member of Any
Array("1","2","3").fold(0)(_ + _.toInt)
^

此错误消息是什么意思?

文档中的这一行也让我感到困惑。

z - a neutral element for the fold operation; may be added to the result an arbitrary number of times, and must not change the result (e.g., Nil for list concatenation, 0 for addition, or 1 for multiplication.)

为什么它会被添加任意次数?我认为折叠的工作方式不同。

最佳答案

根据 Scala 的定义,foldLeft 是线性操作,而 fold 允许是树操作。例如:

List(1,2,3,4,5).foldLeft(0)(_ + _)
// This is the only valid order of operations
0+1 = 1
1+2 = 3
3+3 = 6
6+4 = 10
10 + 5 = 15
15 // done

List(1,2,3,4,5).fold(0)(_ + _)
// This is valid
0+1 = 1 0+3 = 3 0+5 = 5
1+2 = 3 3+4 = 7 5
3 + 7=10 5
10 + 5 = 15
15 // done

为了允许对顺序列表进行任意树分解,您必须有一个不执行任何操作的零(这样您就可以将它添加到树中任何需要的地方),并且您必须创建与您将其作为二进制参数,因此类型不会根据您分解树的方式而改变。

(能够作为树进行评估对于并行化来说是很好的。如果您希望能够随时转换输出时间,则需要组合运算符标准起始值-transforms-sequence-element-to-desired-type 函数就像 foldLeft 一样。Scala 有这个函数并将其称为 aggregate,但在某些方面这更像 >foldLeftfold 是。)

关于scala - Fold 和 FoldLeft 方法区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11319111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com