liveBook · Manning

Recursion

As explained in Elixir in Action, Third Edition

Recursion is a technique in which a computation invokes itself on a smaller, simpler, or continuing input until reaching a terminating or deliberately nonterminating case.

Recursion is Elixir’s principal mechanism for looping: a function processes an input, calls itself with a smaller or continuing input, and stops when a matching clause reaches a base case. Elixir omits while-style loops, although production code often hides recursion behind higher-level abstractions. section 3.4 section 3.4.1

A recursive Elixir function typically combines:

  • Pattern-matching clauses that distinguish the stopping input from the input still requiring work. section 3.3.1
  • A base clause that returns a result directly, such as 0 for the sum of an empty list. section 3.4.1
  • A recursive clause that consumes part of the input and calls the function on the remainder. section 3.3.1
  • Tail recursion when the recursive call is the final operation, allowing arbitrarily long iterations without additional stack space. section 3.4.2

Summing a list

A direct recursive definition mirrors the data: an empty list sums to 0, while a nonempty list adds its head to the sum of its tail. For large or arbitrarily long iterations, an accumulator-based helper makes the recursive call tail-positioned.

Listing 3.9 Tail-recursive sum of the first n natural numbers (sum_list_tc.ex)
defmodule ListHelper do
 def sum(list) do
   do_sum(0, list)
 end

 defp do_sum(current_sum, []) do
   current_sum
 end

 defp do_sum(current_sum, [head | tail]) do
   new_sum = head + current_sum
   do_sum(new_sum, tail)
 end
end

Use the accumulator-based implementation to compare a public wrapper with a private tail-recursive worker, including its empty-list termination clause. section 3.4.2

How Elixir in Action, Third Edition covers it

How deep it goes
Explains base cases, recursive clauses, list decomposition, tail-call optimization, accumulators, and stack-space behavior.
Examples
Demonstrates factorial, natural-number printing, direct list summation, and accumulator-based tail-recursive summation.
What it assumes
Assumes basic Elixir functions and data structures while teaching pattern matching, multiclause dispatch, list decomposition, and termination through examples.
What you can do after
Build it from scratch: write recursive loops with terminating clauses, process lists, and convert suitable functions to tail-recursive form.
How it connects
Connects recursion with pattern matching, multiclause functions, tail-call optimization, higher-order functions, Enum, Stream, comprehensions, and BEAM processes.

Also explained in

Compare how 23 books explain recursion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.