foldLeft v. foldRight - does it matter?

后端 未结 6 2061
迷失自我
迷失自我 2020-12-24 14:27

Previously, Nicolas Rinaudo answered my question on Scala\'s List foldRight Always Using foldLeft?

Studying Haskell currently, my understanding is that foldRig

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-24 14:44

    It depends, consider the following:

    scala> val l = List(1, 2, 3)
    l: List[Int] = List(1, 2, 3)
    
    scala> l.foldLeft(List.empty[Int]) { (acc, ele) => ele :: acc }
    res0: List[Int] = List(3, 2, 1)
    
    scala> l.foldRight(List.empty[Int]) { (ele, acc) => ele :: acc }
    res1: List[Int] = List(1, 2, 3)
    

    As you can see, foldLeft traverses the list from head to the last element. foldRight on the other hand traverses it from the last element to head.

    If you use folding for agregation, there should be no difference:

    scala> l.foldLeft(0) { (acc, ele) => ele + acc }
    res2: Int = 6
    
    scala> l.foldRight(0) { (ele, acc) => ele + acc }
    res3: Int = 6
    

提交回复
热议问题