Scala – Reduce Right

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

Scala Tutorial ReduceRight Function Example

 

The reduceRight is relevant to both Scala’s Mutable and Immutable assortment information structures.

The reduceRight technique takes an affiliated twofold administrator work as boundary and will utilize it to implode components from the assortment. The request for crossing the components in the assortment is from option to left and henceforth the name reduceRight. In contrast to the foldRight technique, reduceRight doesn’t permit you to likewise determine 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 applies the binary operator to the elements of the collection starting from the leftmost element and accumulates a result until all elements are process .Scala Tutorial ReduceRight Function Example

In this example, the binary operator (acc, elem) => acc * elem is applies iteratively to compute the product of all elements in the list starting from the leftmost element.

Understanding how to use reduceLeft is important for functional programming in Scala,and as it allows for elegant and in a concise solutions to aggregation tasks. By leveraging reduceLeft, developers can perform complex computations on collections while adhering to functional programming principles.

use case 1:

find the sum of the elements using reduceRight function

scala> val donutPrices: Seq[Double] = Seq(4.5, 2.0, 2.5)
scala> println(s"Elements of donutPrices = $donutPrices")
scala> val sum: Double = donutPrices.reduceRight(_ + _)

2use case 2:

Find the cheapest donut using reduceRight function

We can also use the reduceRight method to find the minimum element in the Sequence of donut prices as shown below.

scala> val donutPrices: Seq[Double] = Seq(4.5, 2.0, 2.5)
scala> println(s"Elements of donutPrices = $donutPrices")
scala> println(s"Cheapest donut price = ${donutPrices.reduceRight(_ min_)}")

use case 3:

Find the most expensive donut using reduceRight function
we can use the reduceRight method to find the maximum element in the Sequence of donut prices.

scala> val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
scala> println(s"Elements of donutPrices = $donutPrices")
scala> println(s"Cheapest donut price = ${donutPrices.reduceRight(_ max _)}")
0
0

Quick Support

image image