Scala Tutorial - Learn How To Use ReduceRight Function With Examples

By Nadim Bahadoor | Last updated: November 29, 2017 at 21:29 pm

Overview

In this tutorial, we will learn how to use the reduceRight function with examples on collection data structures in Scala. The reduceRight function is applicable to both Scala's Mutable and Immutable collection data structures.

 

The reduceRight method takes an associative binary operator function as parameter and will use it to collapse elements from the collection. The order for traversing the elements in the collection is from right to left and hence the name reduceRight. Unlike the foldRight method, reduceRight does not allow you to also specify an initial value.

 

As per the Scala documentation, the definition of the reduceRight method is as follows:

def reduceRight[B >: A](op: (B, A) ⇒ B): B

 

The reduceRight method is a member of the TraversableOnce trait. You should bear in mind that using reduceRight comes with an overhead with elements from the collection being initially reversed as shown in it's implementation from the Scala source code of TraversableOnce trait. Prefer to use reduceLeft.


  def reduceRight[B >: A](op: (A, B) => B): B = {
    if (isEmpty)
      throw new UnsupportedOperationException("empty.reduceRight")

    reversed.reduceLeft[B]((x, y) => op(y, x))
  }

Steps

1. How to initialize a sequence of donut prices

The code below show how to initialize a Sequence of type Double to represent donut prices..

println("Step 1: How to initialize a sequence of donut prices")
val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donutPrices = $donutPrices")

You should see the following output when you run your Scala application in IntelliJ:


Step 1: How to initialize a sequence of donut prices
Elements of donutPrices = List(1.5, 2.0, 2.5)

 

2. How to find the sum of the elements using reduceRight function

The code below shows how to use the reduceRight method to find the sum of the Sequence of type Double from Step 1, that is, the sum of donut prices.


println("\nStep 2: How to find the sum of the elements using reduceRight function")
val sum: Double = donutPrices.reduceRight(_ + _)
println(s"Sum of elements from donutPrices = $sum")

You should see the following output when you run your Scala application in IntelliJ:


Step 2: How to find the sum of the elements using reduceRight function
Sum of elements from donutPrices = 6.0

 

3. How to find the sum of elements using reduceRight function explicitly

In Step 2, we used the reduceRight method along with the wildcard operator. The example below is similar to the one in Step 2 except that we are using the reduce method explicitly to capture the operator function.


println("\nStep 3: How to find the sum of elements using reduceRight function explicitly")
val sum1: Double = donutPrices.reduceRight((a, b) => a + b)
println(s"Sum of elements from donutPrices by calling reduceRight function explicitly= $sum1")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to find the sum of elements using reduceRight function explicitly
Sum of elements from donutPrices by calling reduceRight function explicitly= 6.0

 

4. How to 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.


println("\nStep 4: How to find the cheapest donut using reduceRight function")
println(s"Cheapest donut price = ${donutPrices.reduceRight(_ min _)}")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to find the cheapest donut using reduceRight function
Cheapest donut price = 1.5

 

5. How to find the most expensive donut using reduceRight function

Similar to Step 4, we can use the reduceRight method to find the maximum element in the Sequence of donut prices.


println("\nStep 5: How to find the most expensive donut using reduceRight function")
println(s"Most expensive donut price = ${donutPrices.reduceRight(_ max _)}")

You should see the following output when you run your Scala application in IntelliJ:


Step 5: How to find the most expensive donut using reduceRight function
Most expensive donut price = 2.5

 

6. How to initialize a Sequence of donuts

The reduce method is of course not limited to Sequence of type Double. Let's create a Sequence of type Double to represent a Sequence of donuts.


println("\nStep 6: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

 

7. How to concatenate the elements from the sequence using reduceRight function

In the mkString method tutorial, we showed how to conveniently create String representation of collection. The code below will instead use the reduceRight method to concatenate the String elements from the Sequence of donuts.


println("\nStep 7: How to concatenate the elements from the sequence using reduceRight function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduceRight((left, right) => left + ", " + right)}")

You should see the following output when you run your Scala application in IntelliJ:


println("\nStep 7: How to concatenate the elements from the sequence using reduceRight function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduceRight((left, right) => left + ", " + right)}")

 

8. How to declare a value function to concatenate donut names

Let's redo the example from Step 7 and show how to declare a value function which will encapsulate combining donut elements of type String.


println("\nStep 8: How to declare a value function to concatenate donut names")
val concatDonutNames: (String, String) => String = (left, right) => {
 left + ", " + right
}
println(s"Value function concatDonutNames = $concatDonutNames")

You should see the following output when you run your Scala application in IntelliJ:


Step 8: How to declare a value function to concatenate donut names
Value function concatDonutNames = <function2>

 

9. How to pass a function to reduceRight function

With the value function from Step 8, we can now pass it through to the reduceRight method to concatenate our donut String elements as follows.


println("\nStep 9: How to pass a function to reduceRight function")
println(s"Elements of donuts sequence concatenated by passing function to the reduceRight function = ${donuts reduceRight concatDonutNames}")

You should see the following output when you run your Scala application in IntelliJ:


Step 9: How to pass a function to reduceRight function
Elements of donuts sequence concatenated by passing function to the reduceRight function = Plain Donut, Strawberry Donut, Glazed Donut

 

10. How to use reduceRightOption to avoid exception if the collection is empty

You should note that calling the reduceRight method on an empty collection will throw an exception. To avoid an exception being thrown, you can make use of the convenient reduceRightOption method instead.


println("\nStep 10: How to use reduceRightOption to avoid exception if the collection is empty")
println(s"Using reduceRightOption will NOT throw any exception = ${Seq.empty[String].reduceRightOption(_ + ", " + _)}")

You should see the following output when you run your Scala application in IntelliJ:


Step 10: How to use reduceRightOption to avoid exception if the collection is empty 
Using reduceRightoption will NOT throw any exception = None

NOTE:

This concludes our tutorial on Learn How To Use ReduceRight Function With Examples and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to initialize a sequence of donut prices
  • How to find the sum of the elements using reduceRight function
  • How to find the sum of elements using reduceRight function explicitly
  • How to find the cheapest donut using reduceRight function
  • How to find the most expensive donut using reduceRight function
  • How to initialize a Sequence of donuts
  • How to concatenate the elements from the sequence using reduceRight function
  • How to declare a value function to concatenate donut names
  • How to pass a function to reduceRight function
  • How to use reduceRightOption to avoid exception if the collection is empty

Tip

  • Review the tutorials on Mutable and Immutable collection data structures in Scala.

Source Code

The source code is available on the allaboutscala GitHub repository.

 

What's Next

In the next tutorial, I will show you how to use reverse function.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Senior Principal Engineer | Elsevier
Founder of allaboutscala.com. I have over 10 years of experience in building large scale real-time trading systems in the financial industry. Passionate about Distributed Systems, Scala, Big Data and Functional Programming. Stay in touch for upcoming tutorials!
Other allaboutscala.com tutorials you may like:

Share this article on