In Elixir the most used tool for iterating through collections is recursion. Most of us know recursion as referencing a function within its own invocation. This function gets called until it arrives at a base terminating case or after it has been called a fixed number of times. An example of a recursive function in elixir would be as follows:
def multiply_numbers2([head | tail]) when is_number(head) do
multiply_numbers2(tail) * head
def multiply_numbers2([_head | tail]) do
def multiply_numbers2() do
The problem with this implementation is that at greater collection sizes, the compiler will have to use a linear amount of memory in order to generate the desired outcome. This is because, as written, each following stack directly relies on the output of the stack before it. As a result, the compiler and the garbage collector must keep each previous stack around until the final terminating function call.
Elixir however allows for something called tail end optimization. The idea used by compilers to optimize tail-recursive functions is simple: since the recursive call is the last statement in the function call, there is nothing left to do in the current function, so saving the current function’s stack frame is of no use. We could rewrite the above function as:
def multiply_numbers(list) do
defp do_mult_numbers([head | tail], prod) when is_number(head) do
do_mult_numbers(tail, prod * head)
defp do_mult_numbers([_head | tail], sum) do
defp do_mult_numbers(, prod) do
Here as we can see, we are making a public call to our private recursive function. Instead of having the math be the last thing we do in our function calls, we make the function call itself be the last thing we do. Since we are keeping track of state between calls with the product variable, there is no reason for the compiler to remember the state of the previous stack. Therefore, we are able to achieve a constant space complexity as opposed to a linear one.
Tail end recursion is a power optimization tool that should be taken advantage of whenever possible!