Scala Tutorial - Learn How To Use Fold Function With Examples

By Nadim Bahadoor | Last updated: January 8, 2018 at 21:29 pm

Overview

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

 

The fold method takes an associative binary operator function as parameter and will use it to collapse elements from the collection. The fold method allows you to also specify an initial value.

 

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


def fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1

 

The fold method 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 fold function

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


println("\nStep 2: How to sum all the donut prices using fold function")
val sum = prices.fold(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 fold function
Sum = 6.0

NOTE:

  • Note that we passed in a default or initial value of 0.0 to the fold 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 fold 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 fold method.



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

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 fold function
All donuts = Plain Donut Strawberry Donut Glazed Donut 

 

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 = (s1, s2) => s1 + s2 + " Donut "
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>

 

6. How to create a String of all donuts using value function from Step 5 and fold 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 fold method.


println("\nStep 6: How to create a String of all donuts using value function from Step 5 and fold function")
println(s"All donuts = ${donuts.fold("")(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 fold function
All donuts = Plain Donut Strawberry Donut Glazed Donut 

This concludes our tutorial on Learn How To Use Fold 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 fold function
  • How to initialize a Sequence of donuts
  • How to create a String of all donuts using fold 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 fold 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 foldLeft 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

  • Jim Brashear

    Code in question:

    val donuts: Seq[String] = Seq(“Plain”, “Strawberry”, “Glazed”)
    println(“nStep 4: How to create a String of all donuts using fold function”)
    println(s”All donuts = ${donuts.fold(“”)((a, b) => a + b + ” Donut “)}”)

    So when doing this fold as shown in your tutorial – it raises 3 questions:

    1. What does a and b represent? Is a the type and b the value (aka Seq and the values of Seq)?
    2. Assuming that’s right – why are you concatenating them with a+b? I’m still not sure what is exactly happening on the fold that there’s 2 variables in question and that they’d need concatenated.
    3. Also the .fold(“”) – what does the (“”) represent?

    • allaboutscala

      Hi Jim,

      Thank you for your question. I’ve updated the variable names to make it easier to distinguish between fold’s accumulator w.r.t. the next item in the fold.

      1. a is the accumulator and i’ve renamed it to acc. b is the next item in the donuts sequence which is of type String. On each iteration of fold, the states of the accumulator would be as follows:
      acc =
      b = Plain
      acc = Plain Donut
      b = Strawberry
      acc = Plain Donut Strawberry Donut
      b = Glazed
      acc = Plain Donut Strawberry Donut Glazed Donut

      2. I’m using fold to iterate over a String of donut items in a Sequence and adding the suffix “Donut” to each donut name. I’ve detailed each iteration for the accumulator in reply to question 1.

      3. fold takes an initial value and in this case the initial value is an empty String, i.e. “”. Note that reduce will have similar behaviour as fold, except that reduce does not allow an initial value.

      Hope the comments above help clarify the examples.

      Cheers,
      Nadim

      • Jim Brashear

        Sir – it’s a rarity that I’ve seen a developer in the Scala community be so helpful and informative. I very much appreciate you taking the time to explain and show clear/concise and understandable examples. THANK YOU – and I’ll be sharing this explanation with a few developers on my team that have also been confused by this function.

        • allaboutscala

          Hi Jim
          Thank you very much for your kind note. I try to make time to answer questions as much as I can 🙂 Also thank you for offering to help share my tutorials with your team – very much appreciated!
          Cheers,
          Nadim