Difference between fold and foldLeft or foldRight?

前端 未结 7 1770
星月不相逢
星月不相逢 2020-11-29 20:43

NOTE: I am on Scala 2.8—can that be a problem?

Why can\'t I use the fold function the same way as foldLeft or foldRight?

相关标签:
7条回答
  • 2020-11-29 21:42

    Short answer:

    foldRight associates to the right. I.e. elements will be accumulated in right-to-left order:

    List(a,b,c).foldRight(z)(f) = f(a, f(b, f(c, z)))
    

    foldLeft associates to the left. I.e. an accumulator will be initialized and elements will be added to the accumulator in left-to-right order:

    List(a,b,c).foldLeft(z)(f) = f(f(f(z, a), b), c)
    

    fold is associative in that the order in which the elements are added together is not defined. I.e. the arguments to fold form a monoid.

    0 讨论(0)
提交回复
热议问题