Recursion replaces loops

Elixir has no for loop that ticks a counter and no while loop that rechecks a condition. Repetition happens when a function calls itself with new arguments, and a clause that matches the end of the input stops the chain. This lesson writes that shape by hand, then shows the standard library calls that do it for everyday work.

A function calls itself

The base clause matches the value that ends the work, and the recursive clause does one step and calls the same function with a smaller argument. The two clauses are ordinary patterns, so the base clause comes first and the recursive one accepts everything else in the range it expects:

countdown.exs

defmodule Count do def down(0), do: IO.puts("done") def down(n) do IO.puts(n) down(n - 1) end end Count.down(3)

elixir countdown.exs

3
2
1
done

The call down(3) prints and calls down(2), which calls down(1), which calls down(0), and the base clause ends the chain. Nothing changes in place: each call has its own n, and the old value is still there in the frame that waits.

An accumulator carries the result

A function that returns a value built along the way carries it in an accumulator, one argument that holds the work done so far. A public function starts the accumulator and a private helper does the walk, so the caller never passes the extra argument:

sum.exs

defmodule Sum do def total(list), do: total(list, 0) defp total([], acc), do: acc defp total([head | tail], acc), do: total(tail, acc + head) end IO.puts(Sum.total([1, 2, 3]))

elixir sum.exs

6

The empty list is the base case and returns the accumulator. The other clause takes the head, adds it to the accumulator and walks the tail. The list patterns of the pattern matching lesson are what make the walk short: no index, no length call, no counter.

The tail call

A recursive call in the last position of a clause is a tail call. The virtual machine reuses the frame for it, so the depth of the recursion does not grow with the length of the input. The factorial below keeps the product in the accumulator and calls itself last:

fact.exs

defmodule Fact do def of(n), do: go(n, 1) defp go(0, acc), do: acc defp go(n, acc), do: go(n - 1, n * acc) end IO.puts(Fact.of(5)) IO.puts(Fact.of(20))

elixir fact.exs

120
2432902008176640000

The multiplication happens in the argument, before the call, so nothing is left to do after the call returns. A version written as n * go(n - 1, 1) multiplies after the call returns, keeps every frame on the stack and is not a tail call. The accumulator is what turns the second shape into the first.

Reach for Enum first

Hand-written recursion is how the idea works, and the standard library already writes it for the shapes a program meets every day. Enum.map/2, Enum.filter/2, Enum.reduce/3 and Enum.sum/1 are the calls a real script uses:

enum.exs

total = [1, 2, 3] |> Enum.map(&(&1 * 2)) |> Enum.sum() IO.puts(total)

elixir enum.exs

12

The pipeline says what happens to the list, and the library handles the walk. Write a recursive helper when the step is genuinely new, and use the Enum function when the step is a map, a filter or a fold. The Enum lesson takes the whole module apart.

The mistake: no base clause

A recursive function needs the clause that ends the walk. Without it the argument eventually reaches a shape no clause accepts, and the program stops with a FunctionClauseError that names the function and the argument:

nobase.exs

defmodule Sum do def total([head | tail], acc), do: total(tail, acc + head) end IO.puts(Sum.total([1, 2], 0))

elixir nobase.exs

** (FunctionClauseError) no function clause matching in Sum.total/2

    The following arguments were given to Sum.total/2:

        # 1
        []

        # 2
        3

    nobase.exs:2: Sum.total/2
    nobase.exs:5: (file)

The report names the arguments it was given, the empty list and the accumulated total, and the two places of the call. Add defp total([], acc), do: acc and the walk ends. A recursive function that never reaches its base clause instead runs until the machine runs out of memory, which is the failure mode to avoid when the base case is a condition rather than a shape.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What ends a recursive function in Elixir?

    Answer

    A base clause that matches the end of the input

    The base clause is a pattern that stops the chain by not calling the function again.

  2. What is an accumulator in a recursive function?

    Answer

    An argument that carries the work done so far

    The accumulator is passed to the next call, so the result is built on the way.

  3. What makes a recursive call a tail call?

    Answer

    It is the last thing the clause does, with no work left after it returns

    A tail call leaves nothing to do after it returns, so the VM can reuse the frame.

  4. Which call replaces a hand-written walk over a list in everyday code?

    Answer

    Enum.map/2 or Enum.reduce/3

    Enum holds the mapped, filtered and folded walks, and it is the first choice.

  5. What does this program print? defmodule Count do def down(0), do: IO.puts("done") def down(n) do IO.puts(n) down(n - 1) end end Count.down(2)

    Answer

    2 / 1 / done

    Each call prints its number and the base clause prints done at zero.

  6. What does this program print? defmodule Sum do def total(list), do: total(list, 0) defp total([], acc), do: acc defp total([head | tail], acc), do: total(tail, acc + head) end IO.puts(Sum.total([1, 2, 3]))

    Answer

    6

    The accumulator starts at zero and takes each element in turn, so the total is 6.

  7. What does this program print? defmodule Fact do def of(n), do: go(n, 1) defp go(0, acc), do: acc defp go(n, acc), do: go(n - 1, n * acc) end IO.puts(Fact.of(5))

    Answer

    120

    The walk multiplies 5, 4, 3, 2 and 1 into the accumulator, which gives 120.

  8. What does this program print? total = [1, 2, 3] |> Enum.map(&(&1 * 2)) |> Enum.sum() IO.puts(total)

    Answer

    12

    The map doubles each element and the sum adds 2, 4 and 6.

  9. What does this program do? defmodule Sum do def total([head | tail], acc), do: total(tail, acc + head) end IO.puts(Sum.total([1, 2], 0))

    Answer

    A FunctionClauseError, because the empty list matches no clause

    The walk reaches [] with no base clause, so the call has nowhere to go.

  10. Why does the recursive clause of Sum.total/2 call total(tail, acc + head) and not total(tail, acc)?

    Answer

    The head has to be added to the accumulator before the walk continues

    The accumulator carries the sum of the elements already seen, so each head is added on the way.

Article author: Arthur Isaev