问题描述
我不确定 Scala 中 fold
和 foldLeft
之间有什么区别.
I am not sure what is the difference between fold
and foldLeft
in Scala.
问题 fold 和 foldLeft 或 foldRight 之间的区别?有一个关于订购的答案.这是可以理解的.但我仍然不明白为什么会这样(来自 REPL):
The question Difference between fold and foldLeft or foldRight? has an answer that talks about ordering. That is understandable. But I still don't understand why this works (from 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)
^
此错误消息是什么意思?
What does this error message mean?
文档中的这一行也让我感到困惑.
This line from the documentation is also confusing to me.
z - 折叠操作的中性元素;可以添加到结果任意次数,并且不得更改结果(例如,Nil 表示列表连接,0 表示添加,或 1 表示乘法.)
为什么要添加任意次数?我认为折叠的工作方式不同.
Why will it be added an arbitrary number of times? I thought folding works differently.
推荐答案
在 Scala 中定义,foldLeft
是线性操作,而 fold
允许是树操作.例如:
As defined by Scala, foldLeft
is a linear operation while fold
is allowed to be a tree operation. For example:
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
为了允许顺序列表的任意树分解,你必须有一个不做任何事情的零(所以你可以在树中任何你需要的地方添加它)并且你必须创建相同类型的东西您将其作为二元参数,因此类型不会因您分解树的方式而改变.
In order to allow arbitrary tree decompositions of a sequential list, you must have a zero that doesn't do anything (so you can add it wherever you need it in the tree) and you must create the same sort of thing that you take as your binary arguments so the types don't change on you depending on how you decompose the tree.
(能够像树一样求值对于并行化来说非常好.如果您希望能够随时转换输出时间,您需要一个组合运算符和一个标准的起始值-transforms-sequence-element-to-desired-type 函数就像 foldLeft
一样.Scala 有这个,并称之为 aggregate
,但在某些方面这更像 foldLeft
比 fold
是.)
(Being able to evaluate as a tree is nice for parallelization. If you want to be able to transform your output time as you go, you need both a combination operator and a standard start-value-transforms-sequence-element-to-desired-type function just like foldLeft
has. Scala has this and calls it aggregate
, but in some ways this is more like foldLeft
than fold
is.)
这篇关于fold 和 foldLeft 方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!