O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Keeping Track of Values During Recursion

So far you’ve seen how to process each element in a list, but what if we want to sum all of the elements? The difference here is that we need to remember the partial sum as we process each element in turn.

In terms of a recursive structure, it’s easy:

  • sum([]) 0

  • sum([ head |tail ]) total + sum(tail)

But the basic scheme gives us nowhere to record the total as we go along. Remember that one of our goals is to have immutable state, so we can’t keep the value in a global or module-local variable.

But we can pass the state in a function’s parameter.

lists/sum.exs
 
defmodule​ MyList ​do
 
def​ sum([], total), ​do​: total
 
def​ sum([ head | tail ], total), ​do​: sum(tail, head+total)
 
end

Our sum

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required