Scala – Reduce Left

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

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.

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(_ + _)

use 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 _)}")

Quick Support

image image