简体   繁体   中英

FoldLeft via FoldRight in Scala again

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.

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 (ie 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM