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
Here are the prototypes of the methods
fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1
foldLeft[B](z: B)(f: (B, A) ⇒ B): B
So, for fold the result is of type A1 >: A
instead of any B
. Moreover, as specified in the doc, for fold
the order is not
When typing scala> Array("1","2","3").fold(0)(_ + _.toInt)
you assume that 0
, an int
is a subtype of String
. This is why the compiler throws an error.
Here we have to see the implementation of fold
to understand what happens. Here is what we get:
def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1 = foldLeft(z)(op)
So basically, fold
is an implementation of foldleft
with a constraint on the output type.
We can now see that z
will in practice be used the same way as in foldleft
. So we can just conclude that this comment was made because nothing assures that behavior in future implementations. We can already see it now, with parallels:
def fold[U >: T](z: U)(op: (U, U) => U): U = {
executeAndWaitResult(new Fold(z, op, splitter))
}