Reducing a List to a Single Value

Learn how to reduce a list to a single value.

We'll cover the following

In the map function, we just wrote the idea of applying a function to each element of a list independently.

Why do we need it ?

What should we do if we want to apply that function across the elements? How could we create an abstraction that would let us sum a list, find the product of its elements, or find the largest element?

The sum function reduces a collection to a single value. Other functions need to do something similar: return the greatest/least value, the product of the elements, and so on. How can we write a general-purpose function that reduces a collection to a value?

Solution

  • For this purpose, it has to take a collection.
  • We also know we need to pass in some initial value (just like our sum/1 function passed a 0 as an initial value to its helper).
  • Additionally, we need to pass in a function that takes the current value of the reduction along with the next element of the collection and returns the next value of the reduction.

So, it looks like our reduce function will be called with three arguments: reduce(collection, initial_value, fun).

Now, let’s think about the recursive design:

  • reduce([ ], value, _fun) → value
  • reduce([ head | tail ], value, fun) → reduce(tail, fun.(head, value), fun)

The reduce function applies the function to the list’s head and the current value and then passes the result as the new current value when reducing the list’s tail.

Get hands-on with 1400+ tech skills courses.