• Share Ideas, Start Something Good.

### Scala – Reduce Right

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

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.

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

use 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