Reducing a List to a Single Value
The map/2 function we just wrote abstracts the idea of applying a function to each element of a list independently.
But what if we want to apply that function across the elements? How could we create an abstraction that would let us sum a list, or 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, a string containing a concatenation of elements, and so on. How can we write a general-purpose function that reduces a collection to a value?
We know it has to take a collection. We also know we need to pass in some initial value (just like ...
Get Programming Elixir ≥ 1.6 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.