Recursion replaces loops

Erlang has no for and no while. Repetition is a function that calls itself: one clause answers the smallest input, and the other clause does one step and calls again with less. The shape is small, and the position of that call decides whether the loop uses constant memory or grows a stack.

Base case first

A recursive function starts with its base case, the input small enough to answer directly. Write it first, so the function always has a way to stop. Here the base case prints the last line and the other clause counts down:

countdown.erl

-module(countdown). -export([count/1]). count(0) -> io:format("done~n"); count(N) -> io:format("~p~n", [N]), count(N - 1).

erlc countdown.erl

erl -noshell -eval 'countdown:count(3), halt().'

3 2 1 done

The clause count(0) matches only zero, and count(N) matches every other integer, so the clauses must stay in this order: an unguarded clause first would swallow the base case. A call with a value that never reaches zero, such as a negative number, recurses forever; the function trusts its caller to pass a natural number, which is the contract a typespec can state.

One step

The recursive step moves the input one unit toward the base case. Each call works on a smaller problem, and the calls stop when the base case matches. The shell transcript above is also the proof of the order: the numbers print on the way down and done on the way out.

A missing base case is an infinite call chain. In this form the call is the last thing the clause does, so the chain grows in constant memory and never stops; the process runs until it is killed. That is why the base case is written before the step and reviewed in the same breath.

Tail recursion

A call is in tail position when it is the last thing the function does, with no arithmetic or constructor waiting for its result. The runtime reuses the stack frame of a tail call, so a tail recursive function runs in constant memory however long the input is. Move the result into an extra argument, the accumulator, and the call becomes the last expression:

mysum.erl

-module(mysum). -export([sum/1, sum_acc/2]). sum([]) -> 0; sum([Head | Tail]) -> Head + sum(Tail). sum_acc([], Acc) -> Acc; sum_acc([Head | Tail], Acc) -> sum_acc(Tail, Acc + Head).

sum/1 is not tail recursive: the addition waits for sum(Tail) to return, so each element adds a stack frame. sum_acc/2 adds first and calls last, so it uses one frame for the whole list. Both answer the same number:

erlc mysum.erl

erl -noshell -eval 'io:format("~p~n", [mysum:sum([1, 2, 3])]), io:format("~p~n", [mysum:sum_acc([1, 2, 3], 0)]), halt().'

6 6

The accumulator

An accumulator is a partial answer that travels with the call. The public function starts it, and the private one carries it; the base case returns it. The convention is to export the two-argument version only when a caller needs a non-zero start, and to keep the one-argument function as the readable entry:

sum_acc(List, 0) is the call the one-argument version would make. The accumulator also gives the loop a place to reverse a list, count, or keep the best value so far, which is why every loop in the standard library is written this way.

A real example

A factorial shows both forms in one module. The first is the textbook definition, and the second moves the multiplication into the accumulator. For five the answers agree; for a large number the first builds a deep stack and the second does not:

factorial.erl

-module(factorial). -export([fact/1, fact/2]). fact(0) -> 1; fact(N) -> N * fact(N - 1). fact(0, Acc) -> Acc; fact(N, Acc) -> fact(N - 1, N * Acc).

erlc factorial.erl

erl -noshell -eval 'io:format("~p~n", [factorial:fact(5)]), io:format("~p~n", [factorial:fact(5, 1)]), halt().'

120 120

fact/1 and fact/2 share a name and differ in arity, so they are two functions, not a clash. The public fact/1 could be a one-line wrapper around fact(N, 1); here both are exported so the page can call each one and compare. The Lists lesson shows the same loops written with lists:foldl/3, and Performance measures what the difference costs.

Questions

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

  1. What does every recursive function need first?

    Answer

    A base case that answers without calling itself

    Without a base case the calls never stop; the smallest input is answered directly.

  2. When is a call in tail position?

    Answer

    When it is the last thing the function does

    A tail call has no work left after it returns, so the runtime can reuse the stack frame.

  3. What does an accumulator hold?

    Answer

    A partial result carried into the next call

    The accumulator travels as an argument and becomes the answer at the base case.

  4. Which of these two clauses is tail recursive?

    Answer

    sum_acc([H | T], Acc) -> sum_acc(T, Acc + H).

    The addition happens before the call in sum_acc, and nothing waits for the result.

  5. What happens when a recursive function has no base case?

    Answer

    It calls itself until the process is stopped

    Nothing stops the chain, so the process keeps calling until it is killed or runs out of resources.

  6. Why do the clauses count(0) and count(N) have to stay in that order?

    Answer

    The unguarded clause would match zero first

    Clauses are tried in source order, so a general clause above the base case hides it.

  7. What does this module print? -module(q1). -export([main/0, count/1]). count(0) -> done; count(N) -> count(N - 1). main() -> io:format("~p~n", [count(2)]).

    Answer

    done

    The calls go 2, 1, 0, and the base case answers done.

  8. What does this module print? -module(q2). -export([main/0]). sum_acc([], Acc) -> Acc; sum_acc([Head | Tail], Acc) -> sum_acc(Tail, Acc + Head). main() -> io:format("~p~n", [sum_acc([1, 2, 3], 0)]).

    Answer

    6

    The accumulator adds 1, 2 and 3 in turn and the base case returns 6.

  9. What does this module print? -module(q4). -export([main/0, total/1]). total([]) -> 0; total([X | Rest]) -> X + total(Rest). main() -> io:format("~p~n", [total([4, 5, 6])]).

    Answer

    15

    The function adds 4, 5 and 6 on the way back out, and the base case answers 0.

  10. What does this module print? -module(q3). -export([main/0, fact/1]). fact(0) -> 1; fact(N) -> N * fact(N - 1). main() -> io:format("~p~n", [fact(3)]).

    Answer

    6

    3 * 2 * 1 is 6, and the base case answers 1.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev

Изображение баннера