Scala – Reduce Left

  • date 30th May, 2021 |
  • by Prwatech |
  • 0 Comments

Scala Tutorial ReduceLeft Function Example

 

The reduceLeft method is relevant to both Scala’s Mutable and Immutable assortment information structures.The reduceLeft technique takes an affiliated paired administrator work as boundary and will utilize it to implode components from the assortment. The request for navigating the components in the assortment is from left to right and subsequently the name reduceLeft. In contrast to the foldLeft technique, reduceLeft doesn’t permit you to likewise indicate an underlying worth.

The reduceLeft function in Scala is a higher-order function used to iteratively combine elements of a collection from left to right using a binary operation. It is similar to the reduce function but starts the reduction process from the leftmost element of the collection.

The reduceLeft function takes a binary operator as an argument and applies it to the elements of the collection sequentially from the first element to the last, accumulating a single result. The binary operator must be associative, ensuring that the reduction process is consistent regardless of the order of application.

In this example, the reduceLeft function iteratively multiplies each element of the list starting from the leftmost element (1) to compute the factorial (5! = 1 * 2 * 3 * 4 * 5).

The reduceLeft function is particularly useful for aggregating values and performing iterative computations on collections. It provides a functional and concise way to express data transformation operations in Scala. Understanding how to use reduceLeft effectively is essential for mastering functional programming paradigms and leveraging the power of higher-order functions in Scala. Scala Tutorial ReduceLeft Function Example

use case 1:

find the sum of the elements using reduceLeft function

val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donutPrices = $donutPrices")
val sum: Double = donutPrices.reduceLeft(_ + _)

2use case 2:

find the cheapest donut using reduceLeft function

scala> val donutPrices: Seq[Double] = Seq(6.5, 6.0, 8.5)
scala> println(s"Elements of donutPrices = $donutPrices")
scala> println(s"Cheapest donut price = ${donutPrices.reduceLeft(_ min _)}")

use case 3:

find the most expensive donut using reduceLeft function

scala> val donutPrices: Seq[Double] = Seq(6.5, 6.0, 8.5)
scala> println(s"Most expensive donut price = ${donutPrices.reduceLeft(_ max _)}")
0
0

Quick Support

image image