difference between foldLeft and reduceLeft in Scala

后端 未结 7 2029
野性不改
野性不改 2020-12-12 08:49

I have learned the basic difference between foldLeft and reduceLeft

foldLeft:

  • initial value has to be passed
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 09:36

    foldLeft is more generic, you can use it to produce something completely different than what you originally put in. Whereas reduceLeft can only produce an end result of the same type or super type of the collection type. For example:

    List(1,3,5).foldLeft(0) { _ + _ }
    List(1,3,5).foldLeft(List[String]()) { (a, b) => b.toString :: a }
    

    The foldLeft will apply the closure with the last folded result (first time using initial value) and the next value.

    reduceLeft on the other hand will first combine two values from the list and apply those to the closure. Next it will combine the rest of the values with the cumulative result. See:

    List(1,3,5).reduceLeft { (a, b) => println("a " + a + ", b " + b); a + b }
    

    If the list is empty foldLeft can present the initial value as a legal result. reduceLeft on the other hand does not have a legal value if it can't find at least one value in the list.

提交回复
热议问题