I am not sure what is the difference between fold
and foldLeft
in Scala.
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
but this does not:
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 – 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.)
Why will it be added an arbitrary number of times? I thought folding works differently.
Best Answer
As defined by Scala,
foldLeft
is a linear operation whilefold
is allowed to be a tree operation. For example: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.
(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 itaggregate
, but in some ways this is more likefoldLeft
thanfold
is.)