The function must be both commutative and associative.
If our function is f , and our elements are x1 - x4 , then:
foldLeft f(f(f(x1, x2), x3), x4)
foldRight f(x1, f(x2, f(x3, x4)))
Let us use the middle function, which is commutative, but not associative ( (a + b) / 2 == (b + a) / 2 ):
scala> def avg(a: Double, b: Double): Double = (a + b) / 2 avg: (a: Double, b: Double)Double scala> (0 until 10).map(_.toDouble).foldLeft(0d)(avg) res4: Double = 8.001953125 scala> (0 until 10).map(_.toDouble).foldRight(0d)(avg) res5: Double = 0.9892578125
EDITOR: I missed the boat only associatively, but only commutatively. See @jwvy string concatenation example for an associative but not commutative function.
source share