TExcelTAD
Home › Elixir › Elixir Recursion

Elixir Recursion

Elixir has no for or while loops that change a counter, because variables cannot be mutated. Instead, repetition is done by recursion: a function that calls itself on a smaller piece of the problem, plus a base case that stops. In everyday code you will mostly use Enum (next lesson), but Enum itself is built on recursion, and many custom algorithms are easiest to write this way.

Recursion over a list

The [head | tail] pattern splits a list; the empty list [] is the base case:

elixir · try it yourself
defmodule MyList do
  def sum([]), do: 0
  def sum([head | tail]), do: head + sum(tail)

  def len([]), do: 0
  def len([_ | tail]), do: 1 + len(tail)

  def double_all([]), do: []
  def double_all([head | tail]), do: [head * 2 | double_all(tail)]
end

IO.inspect(MyList.sum([4, 8, 15, 16, 23, 42]))
IO.inspect(MyList.len([:a, :b, :c]))
IO.inspect(MyList.double_all([1, 2, 3]))
108
3
[2, 4, 6]

Read sum as two rules: "the sum of an empty list is 0" and "the sum of a list is its head plus the sum of its tail". Each call works on a shorter list, so the recursion always reaches [].

Counting down

Recursion also works on numbers. Guards make the base case explicit:

elixir · try it yourself
defmodule Countdown do
  def run(0), do: IO.puts("Liftoff!")

  def run(n) when n > 0 do
    IO.puts(n)
    run(n - 1)
  end
end

Countdown.run(3)
3
2
1
Liftoff!

Tail calls and accumulators

MyList.sum/1 above has to remember head + for every element until the end is reached, so a list of a million elements builds up a million pending additions. A tail-recursive function makes the recursive call the very last thing it does. The BEAM optimises such calls: they run in constant stack space, like a loop.

The usual trick is an accumulator argument that carries the result so far, plus a public function that sets its starting value:

elixir · try it yourself
defmodule Stats do
  def sum(list), do: sum(list, 0)

  defp sum([], acc), do: acc
  defp sum([head | tail], acc), do: sum(tail, acc + head)

  def reverse(list), do: reverse(list, [])

  defp reverse([], acc), do: acc
  defp reverse([head | tail], acc), do: reverse(tail, [head | acc])
end

IO.inspect(Stats.sum(Enum.to_list(1..1_000_000)))
IO.inspect(Stats.reverse([1, 2, 3, 4]))
500000500000
[4, 3, 2, 1]

sum/1 (public) and sum/2 (private) are different functions because they have different arities. This "public wrapper + private accumulator function" pattern is extremely common.

Notice how reverse builds its result by prepending to the accumulator, which is cheap. A tail-recursive map builds its result backwards the same way and calls reverse once at the end.

Recursion on trees

Recursion shines on nested data. Here a function walks a directory tree made of tuples and adds up the file sizes:

elixir · try it yourself
defmodule Tree do
  def total_size({:file, _name, size}), do: size

  def total_size({:dir, _name, children}) do
    Enum.reduce(children, 0, fn child, acc -> acc + total_size(child) end)
  end

  def print(node, indent \\ 0)

  def print({:file, name, size}, indent) do
    IO.puts(String.duplicate("  ", indent) <> "#{name} (#{size} KB)")
  end

  def print({:dir, name, children}, indent) do
    IO.puts(String.duplicate("  ", indent) <> name <> "/")
    Enum.each(children, &print(&1, indent + 1))
  end
end

project =
  {:dir, "app", [
    {:file, "README.md", 4},
    {:dir, "lib", [{:file, "app.ex", 12}, {:file, "util.ex", 3}]},
    {:dir, "test", [{:file, "app_test.exs", 6}]}
  ]}

Tree.print(project)
IO.puts("total: #{Tree.total_size(project)} KB")
app/
  README.md (4 KB)
  lib/
    app.ex (12 KB)
    util.ex (3 KB)
  test/
    app_test.exs (6 KB)
total: 25 KB

print/2 has a default argument and several clauses, so it starts with a bodiless function head def print(node, indent \\ 0).

When to write recursion yourself

Situation Prefer
map, filter, sum, group, sort a collection Enum functions
lazy or infinite sequences Stream
custom traversal (trees, parsers, state machines) recursion with pattern matching
a process that loops waiting for messages a recursive loop(state) function (see Processes)

Common mistakes

  • Forgetting the base case, or putting it after the general clause: the general clause matches first and the recursion never stops.
  • Building results with acc ++ [x]: each step copies the accumulator. Prepend and reverse.
  • Worrying about stack overflows for body recursion on small lists: the BEAM grows the stack as needed, so body recursion is fine for moderate sizes; tail recursion matters for very long or endless loops.

Test yourself

Which clause is the base case in def len([]), do: 0 / def len([_ | t]), do: 1 + len(t)?

  1. len([_ | t])
  2. len([])
  3. Both
  4. Neither

What makes a function call a tail call?

  1. It is the first line of the function
  2. It is the last thing the function does, with nothing left to compute afterwards
  3. It uses an accumulator named acc
  4. It is in a private function

Why do accumulator functions often end with Enum.reverse/1?

  1. Because prepending builds the list backwards
  2. To sort the result
  3. Because the BEAM reverses lists
  4. To remove duplicates