Open In App

Difference between foldLeft and reduceLeft in Scala

1. Difference between foldLeft and reduceLeft in Scala

Higher-order Scala methods foldLeft and reduceLeft are both used to aggregate the items of a collection. But they exhibit different behaviors:

foldLeft:

reduceLeft:

In conclusion, foldLeft and reduceLeft both conduct left-associative folding of a collection; however, foldLeft permits the specification of a starting value (z), while reduceLeft sets the initial value to the collection's first member.

2. Code and Screenshot

This is an example showing how to use both foldLeft and reduceLeft:

object Main {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5)

    // Using foldLeft to calculate the sum
    val sumFold = numbers.foldLeft(0)((acc, num) => acc + num)
    println("Sum using foldLeft: " + sumFold) // Output: 15

    // Using reduceLeft to calculate the sum
    val sumReduce = numbers.reduceLeft((acc, num) => acc + num)
    println("Sum using reduceLeft: " + sumReduce) // Output: 15
  }
}

Output Screenshot:


Screenshot-(367)

Article Tags :