foldLeft v. foldRight - does it matter?

后端 未结 6 2018
迷失自我
迷失自我 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:42

    scala> val words = List("Hic", "Est", "Index")
    words: List[String] = List(Hic, Est, Index)
    

    Incase of foldLeft: List elements will add to the empty string first and followed

    words.foldLeft("")(_ + _) == (("" + "Hic") + "Est") + "Index"      //"HicEstIndex"
    

    Incase of foldRight: Empty string will add to end of elements

    words.foldRight("")(_ + _) == "Hic" + ("Est" + ("Index" + ""))     //"HicEstIndex"
    

    Both cases will return the same output

    def foldRight[B](z: B)(f: (A, B) => B): B
    def foldLeft[B](z: B)(f: (B, A) => B): B
    

提交回复
热议问题