Scala Tutorial - Learn How To Use ReduceLeft Function With Examples
Overview
In this tutorial, we will learn how to use the reduceLeft function with examples on collection data structures in Scala. The reduceLeft function is applicable to both Scala's Mutable and Immutable collection data structures.
The reduceLeft 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 left to right and hence the name reduceLeft. Unlike the foldLeft method, reduceLeft does not allow you to also specify an initial value.
As per the Scala documentation, the definition of the reduceLeft method is as follows:
def reduceLeft[B >: A](op: (B, A) ⇒ B): B
The reduceLeft method is a member of the TraversableOnce trait.
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 reduceLeft function
The code below shows how to use the reduceLeft 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 reduceLeft function")
val sum: Double = donutPrices.reduceLeft(_ + _)
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 reduceLeft function
Sum of elements from donutPrices = 6.0
3. How to find the sum of elements using reduceLeft function explicitly
In Step 2, we used the reduceLeft 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 reduceLeft function explicitly")
val sum1: Double = donutPrices.reduceLeft((a, b) => a + b)
println(s"Sum of elements from donutPrices by calling reduceLeft 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 reduceLeft function explicitly
Sum of elements from donutPrices by calling reduceLeft function explicitly= 6.0
4. How to find the cheapest donut using reduceLeft function
We can also use the reduceLeft 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 reduceLeft function")
println(s"Cheapest donut price = ${donutPrices.reduceLeft(_ min _)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 4: How to find the cheapest donut using reduceLeft function
Cheapest donut price = 1.5
5. How to find the most expensive donut using reduceLeft function
Similar to Step 4, we can use the reduceLeft method to find the maximum element in the Sequence of donut prices.
println("\nStep 5: How to find the most expensive donut using reduceLeft function")
println(s"Most expensive donut price = ${donutPrices.reduceLeft(_ 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 reduceLeft 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 reduceLeft function
In the mkString method tutorial, we showed how to conveniently create String representation of collection. The code below will instead use the reduceLeft method to concatenate the String elements from the Sequence of donuts.
println("\nStep 7: How to concatenate the elements from the sequence using reduceLeft function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduceLeft((left, right) => left + ", " + right)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 7: How to concatenate the elements from the sequence using reduceLeft function
Elements of donuts sequence concatenated = Plain Donut, Strawberry Donut, Glazed Donut
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 reduceLeft function
With the value function from Step 8, we can now pass it through to the reduceLeft method to concatenate our donut String elements as follows.
println("\nStep 9: How to pass a function to reduceLeft function")
println(s"Elements of donuts sequence concatenated by passing function to the reduceLeft function = ${donuts reduceLeft concatDonutNames}")
You should see the following output when you run your Scala application in IntelliJ:
Step 9: How to pass a function to reduceLeft function
Elements of donuts sequence concatenated by passing function to the reduceLeft function = Plain Donut, Strawberry Donut, Glazed Donut
10. How to use reduceLeftOption to avoid exception if the collection is empty
You should note that calling the reduceLeft method on an empty collection will throw an exception. To avoid an exception being thrown, you can make use of the convenient reduceLeftOption method instead.
println("\nStep 10: How to use reduceLeftOption to avoid exception if the collection is empty")
println(s"Using reduceLeftOption will NOT throw any exception = ${Seq.empty[String].reduceLeftOption(_ + ", " + _)}")
You should see the following output when you run your Scala application in IntelliJ:
Step 10: How to use reduceLeftOption to avoid exception if the collection is empty
Using reduceLeftoption will NOT throw any exception = None
NOTE:
- If you are unsure on how to use option in Scala, feel free to visit our tutorial on using option.
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 reduceLeft function
- How to find the sum of elements using reduceLeft function explicitly
- How to find the cheapest donut using reduceLeft function
- How to find the most expensive donut using reduceLeft function
- How to initialize a Sequence of donuts
- How to concatenate the elements from the sequence using reduceLeft function
- How to declare a value function to concatenate donut names
- How to pass a function to reduceLeft function
- How to use reduceLeftOption to avoid exception if the collection is empty
Tip
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 reduceRight function.