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.
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.
(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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With