Fold and foldLeft method difference

后端 未结 7 803
终归单人心
终归单人心 2021-01-31 01:51

I am not sure what is the difference between fold and foldLeft in Scala.

The question Difference between fold and foldLeft or foldRight? has an

相关标签:
7条回答
  • 2021-01-31 02:27

    General difference

    Here are the prototypes of the methods

    fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1
    foldLeft[B](z: B)(f: (B, A) ⇒ B): B
    

    So, for fold the result is of type A1 >: Ainstead of any B. Moreover, as specified in the doc, for fold the order is not

    About your error

    When typing scala> Array("1","2","3").fold(0)(_ + _.toInt) you assume that 0, an int is a subtype of String. This is why the compiler throws an error.

    About the weird z in fold

    Here we have to see the implementation of fold to understand what happens. Here is what we get:

    def fold[A1 >: A](z: A1)(op: (A1, A1) => A1): A1 = foldLeft(z)(op)
    

    So basically, fold is an implementation of foldleft with a constraint on the output type. We can now see that z will in practice be used the same way as in foldleft. So we can just conclude that this comment was made because nothing assures that behavior in future implementations. We can already see it now, with parallels:

    def fold[U >: T](z: U)(op: (U, U) => U): U = {
      executeAndWaitResult(new Fold(z, op, splitter))
    }
    
    0 讨论(0)
提交回复
热议问题