Scala Tutorial - Learn How To Use FoldRight Function With Examples

By Nadim Bahadoor | Last updated: July 25, 2017 at 14:54 pm

Overview

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

 

The foldRight 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 foldRight. The foldRight method allows you to also specify an initial value.

 

Prefer using foldLeft as opposed to foldRight since foldLeft is fundamental in recursive function and will help you prevent stack-overflow exceptions.

 

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


def foldRight[B](z: B)(op: (A, B) ⇒ B): B

 

The foldRightmethod is a member of the TraversableOnce trait.

Steps

1. How to initialize a sequence of donut prices

The code below shows how to initialize a sequence of donut prices where each element in the sequence is of type Double.


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

 

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


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

 

2. How to sum all the donut prices using foldRight function

The code below shows how to sum all the donut prices from the sequence by using the foldRight method.


println("\nStep 2: How to sum all the donut prices using foldRight function")
val sum = prices.foldRight(0.0)(_ + _)
println(s"Sum = $sum")

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


Step 2: How to sum all the donut prices using foldRight function
Sum = 6.0

NOTE:

  • Note that we passed in a default or initial value of 0.0 to the foldRight method because the sequence of Donuts was of type Double.

3. How to initialize a Sequence of donuts

The code below shows how to initialize a Sequence of donuts where each element is of type String.


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

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

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

 

4. How to create a String of all donuts using foldRight function

The code below shows how to create a String representation for all the donut elements in the Sequence and also append the word Donut to each element using the foldRight method.



println("\nStep 4: How to create a String of all donuts using foldRight function")
println(s"All donuts = ${donuts.foldRight("")((a, b) => a + " Donut " + b)}")

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


Step 4: How to create a String of all donuts using foldRight function
All donuts = Plain Donut Strawberry Donut Glazed Donut 

NOTE:

5. How to declare a value function to create the donut string

The code below shows how to declare a Value Function to encapsulate the behaviour for creating a String representation for all donut elements.


println("\nStep 5: How to declare a value function to create the donut string")
val concatDonuts: (String, String) => String = (a, b) => a + " Donut " + b
println(s"Value function concatDonuts = $concatDonuts")

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


Step 5: How to declare a value function to create the donut string
Value function concatDonuts = <function2>

NOTE:

  • Similar to Step 4, the foldRight implementation is different from foldLeft which was a + b + " Donut " from the previous tutorial.

6. How to create a String of all donuts using value function from Step 5 and foldRight function

The code below shows how to create a String representation for the donut elements by passing through the Value Function from Step 5 to the foldRight method.


println("\nStep 6: How to create a String of all donuts using value function from Step 5 and foldRight function")
println(s"All donuts = ${donuts.foldRight("")(concatDonuts)}")

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


Step 6: How to create a String of all donuts using value function from Step 5 and foldRight function
All donuts = Plain Donut Strawberry Donut Glazed Donut 

This concludes our tutorial on Learn How To Use FoldRight 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 sum all the donut prices using foldRight function
  • How to initialize a Sequence of donuts
  • How to create a String of all donuts using foldRight function
  • How to declare a value function to create the donut string
  • How to create a String of all donuts using value function from Step 5 and foldRight function

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 foreach function.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Senior Software Developer | Nephila Capital
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

  • Satish Sathambakam

    since its foldright, the first element should be glazed donut..so for the first iteration.. a is empty and b is glazed which gives donut glazed. My understanding is final output will be
    donut glazed donut strawberry donut plain
    please correct me if I am wrong if not please correct the content. Thanks

    • Satish Sathambakam

      At the start of execution, the start value that you passed as the first argument is given to your function as its first argument. As the function’s second argument it is given the first item on the list (in the case of fold this may or may not be the actual first item on your list as you will read about below).

      The function is then applied to its two arguments, in this case a simple addition, and returns the result.
      Fold then gives the function the previous return value as its first argument and the next item in the list as its second argument, and applies it, returning the result.
      This process repeats for each item of the list and returns the return value of the function once all items in the list have been iterated over.
      This is a trivial example though. Let’s take a look at something that is more useful. I will use foldLeft in this next example and will explain how it is different from fold later. For now, think of it in the same way as fold.

      Please let me know if this is wrong.

      • allaboutscala

        Hi Satish,

        Thanks for your explanation. My current example is correct but may be unclear about pre-pending to the accumulator as opposed to appending. I will re-work the example and focus primarily on the foldRight behaviour which is what you’ve described. In general, prefer to use foldLeft so you avoid stack-overflows and the additional reverse cost of foldRight.

        Cheers,
        Nadim