Your Turn

  • Exercise: ListsAndRecursion-0

    I defined our sum function to carry a partial total as a second parameter so I could illustrate how to use accumulators to build values. The sum function can also be written without an accumulator. Can you do it?

Generalizing Our Sum Function

The sum function reduces a collection to a single value. Clearly other functions need to do something similar—return the greatest/least value, the product of the elements, a string containing the elements with spaces between them, 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 our sum/1 function passed a 0 as an initial value ...

Get Programming Elixir 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.