Reputation: 109
I know, this question has been asked already. But I have not understood any of the answers. I think I need a more graphic explanation. I can't understand how to "bridge" FoldLeft with FoldRight. I don't care if the anwer is not in Functional Programming in Scala. Thabk you very much in advance.
Upvotes: 0
Views: 652
Reputation: 10882
Just check how those are implemented:
def foldLeft[B](z: B)(op: (B, A) => B): B = {
var result = z
this foreach (x => result = op(result, x))
result
}
def foldRight[B](z: B)(op: (A, B) => B): B =
reversed.foldLeft(z)((x, y) => op(y, x))
foldLeft
traverses collection from left to right applying op
to the result
and current element, while foldRight
traverses reversed collection (i.e. from right to left).
When op
is symmetric and transitive foldLeft
and foldRight
are equivalent, for example:
List(1,2,3).foldLeft(0)(_ + _)
List(1,2,3).foldRight(0)(_ + _)
Result:
res0: Int = 6
res1: Int = 6
But otherwise foldLeft
and foldRight
may produce different results:
List(1,2,3).foldLeft(List[Int]()){case (list, el) => list :+ el }
List(1,2,3).foldRight(List[Int]()){case (el, list) => list :+ el }
Result:
res2: List[Int] = List(1, 2, 3)
res3: List[Int] = List(3, 2, 1)
Upvotes: 1