Google News
logo
Scala - Interview Questions
What is the difference between 'foldLeft' and 'reduceLeft' methods on a collection in Scala?
Both the `foldLeft` and `reduceLeft` methods are used to combine the elements of a collection in Scala. However, there is a slight difference in their behavior:

1. `foldLeft` method :
   * Syntax: `foldLeft[B](z: B)(op: (B, A) => B): B`
   * Purpose: The `foldLeft` method combines the elements of a collection from left to right, starting with an initial value `z` and applying a binary operator `op` to each element along with the accumulated result.
   * Return type: The return type of `foldLeft` is the final accumulated value of type `B`.
   * Example :
     val numbers = List(1, 2, 3, 4, 5)

     val sum = numbers.foldLeft(0)((acc, num) => acc + num)​

     In this example, the `foldLeft` method is called on the `numbers` list. The initial value `0` is provided, and for each element, the binary operator `(acc, num) => acc + num` is applied to accumulate the sum of the elements. The result is the sum of all the numbers.
2. `reduceLeft` method :
   * Syntax: `reduceLeft(op: (A, A) => A): A`
   * Purpose: The `reduceLeft` method combines the elements of a collection from left to right by successively applying a binary operator `op` to pairs of elements, starting from the first element.
   * Return type: The return type of `reduceLeft` is the final result of type `A`.
   * Example :
     val numbers = List(1, 2, 3, 4, 5)

     val product = numbers.reduceLeft((acc, num) => acc * num)​

     In this example, the `reduceLeft` method is called on the `numbers` list. The binary operator `(acc, num) => acc * num` is applied to each pair of elements, starting from the first element, to calculate the product of all the numbers.

The main difference between `foldLeft` and `reduceLeft` lies in the handling of the initial value:

* `foldLeft` requires an explicit initial value (`z`) and applies the binary operator to both the initial value and each element.
* `reduceLeft` does not require an explicit initial value. Instead, it starts the computation with the first element of the collection and applies the binary operator successively to pairs of elements.

When using `foldLeft`, you have more control over the initial value and can handle cases where the collection might be empty. On the other hand, `reduceLeft` assumes that the collection has at least one element and uses its value as the starting point for the computation.
Advertisement