Open In App

Difference between foldLeft and reduceLeft in Scala

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • FoldLeft takes a collection and uses a binary operator to merge its members, beginning at a given initial value (z).
  • As it moves from left to right across the collection, it applies the binary operator to every member and the total result (which is originally z).
  • The total value obtained after all items have been processed is the outcome.
  • foldLeft yields a value (z) of the same type as the original.

reduceLeft:

  • A variant of foldLeft called reduceLeft uses the starting value as the collection’s first member.
  • Beginning with the first member in the collection, it uses a binary operator to combine all of the items.
  • It moves across the collection from left to right, much as foldLeft, applying the binary operator to each element and the total result.
  • The total value obtained after all items have been processed is the outcome.
  • The type returned by reduceLeft is the same as that of the collection’s elements.

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:

Scala
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)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads