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






















