10.20. Walking Through a Collection with the reduce and fold Methods

Problem

You want to walk through all of the elements in a sequence, comparing two neighboring elements as you walk through the collection.

Solution

Use the reduceLeft, foldLeft, reduceRight, and foldRight methods to walk through the elements in a sequence, applying your function to neighboring elements to yield a new result, which is then compared to the next element in the sequence to yield a new result. (Related methods, such as scanLeft and scanRight, are also shown in the Discussion.)

For example, use reduceLeft to walk through a sequence from left to right (from the first element to the last). reduceLeft starts by comparing the first two elements in the collection with your algorithm, and returns a result. That result is compared with the third element, and that comparison yields a new result. That result is compared to the fourth element to yield a new result, and so on.

If you’ve never used these methods before, you’ll see that they give you a surprising amount of power. The best way to show this is with some examples. First, create a sample collection to experiment with:

scala> val a = Array(12, 6, 15, 2, 20, 9)
a: Array[Int] = Array(12, 6, 15, 2, 20, 9)

Given that sequence, use reduceLeft to determine different properties about the collection. The following example shows how to get the sum of all the elements in the sequence:

scala> a.reduceLeft(_ + _)
res0: Int = 64

Don’t let the underscores throw you for a loop; ...

Get Scala Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.