Functions, Recursion and Higher-Order Functions

Article · 4:00

Clauses and guards, case and if, recursion with accumulators, why tail calls matter, and funs.

A module is a file, declared with -module(name) matching the filename, and only what -export([f/1]) lists is callable from outside. Functions are identified by name and arity: add/2 and add/3 are different functions that happen to share a name.

A function is one or more clauses, tried top to bottom, selected by pattern matching the arguments. This replaces most of the branching you would write elsewhere - rather than one function with an if inside it, write two clauses whose patterns differ. Guards refine a clause with when: fact(N) when N > 0 ->. Guards are restricted to a fixed set of side-effect-free expressions - comparisons, type tests, arithmetic - and that restriction is deliberate, since a guard must never do anything.

case Expr of Pattern -> ... end matches inside a function body. if Guard -> ... end has no expression at all, only guards, and is used much less than you would expect. If no clause matches, you get case_clause or if_clause, which is a crash - and in Erlang that is usually the right outcome.

There are no loops. Recursion replaces them, and the distinction that matters is body recursion against tail recursion. A body-recursive function does work after the recursive call returns, so each level must keep a stack frame: fact(N) -> N * fact(N-1) holds N frames. A tail-recursive one makes the recursive call as the very last thing it does, so the BEAM reuses the stack frame and the function runs in constant space - which is what lets a process loop forever. The technique is an accumulator: carry the running result as an extra argument.

This is not a micro-optimisation. Every long-lived Erlang process is a tail-recursive loop, and a process that was accidentally body-recursive grows its stack until the node runs out of memory.

Higher-order functions. A fun is an anonymous function, and functions are values. lists:map/2, lists:filter/2 and lists:foldl/3 cover most of what you would write a loop for; fold is the general one that the other two are special cases of. List comprehensions - [X*2 || X <- L, X > 3] - are frequently clearer than either.

-module(maths).
-export([fact/1, fact_tail/1, classify/1, sum/1, area/1]).

%% ---------------- Clauses, chosen by pattern ----------------
%% Not one function with an if inside it. Two clauses.
fact(0) -> 1;
fact(N) when N > 0 -> N * fact(N - 1).
%%                    ^^^^^^^^^^^^^^^ BODY recursive: the multiply
%%  happens AFTER the call returns, so every level keeps a stack frame.
%%  fact(100000) will exhaust memory.

%% ---------------- Tail recursion, with an accumulator ----------------
fact_tail(N) -> fact_tail(N, 1).        % a public arity-1 wrapper

fact_tail(0, Acc) -> Acc;
fact_tail(N, Acc) when N > 0 ->
    fact_tail(N - 1, N * Acc).          % the LAST thing done: the frame
                                        % is reused. Constant space.
%% This is not a micro-optimisation. Every long-lived process in Erlang
%% is a tail-recursive loop, and one that is accidentally body-recursive
%% grows until the node dies.

%% ---------------- Guards ----------------
classify(N) when is_integer(N), N < 0  -> negative;   % , is andalso
classify(0)                            -> zero;
classify(N) when is_integer(N), N > 0  -> positive;
classify(N) when is_float(N)           -> a_float;
classify(_)                            -> not_a_number.
%%
%% Guards may only contain a fixed set of side-effect-free expressions:
%% comparisons, type tests (is_atom, is_list, is_pid...), arithmetic,
%% and a few BIFs. You cannot call your own function in a guard, and
%% that restriction is the point - a guard must never DO anything.
%% A guard that raises an exception just fails the clause, silently.

%% ---------------- Accumulating over a list ----------------
sum(List) -> sum(List, 0).

sum([], Acc)          -> Acc;
sum([H | T], Acc)     -> sum(T, Acc + H).      % tail recursive

%% ---------------- case, in a body ----------------
area(Shape) ->
    case Shape of
        {circle, R}        -> math:pi() * R * R;
        {rect, W, H}       -> W * H;
        {square, S}        -> S * S;
        Other              -> {error, {unknown_shape, Other}}
    end.
%% No matching clause raises case_clause. Usually that is what you want:
%% a shape you did not plan for is a bug, and it should stop here.

%% ---------------- funs, and the list functions ----------------
%%
%%   Double = fun(X) -> X * 2 end,
%%   Double(21).                                % 42
%%
%%   lists:map(fun(X) -> X * 2 end, [1,2,3]).   % [2,4,6]
%%   lists:filter(fun(X) -> X > 2 end, [1,2,3]).% [3]
%%   lists:foldl(fun(X, Acc) -> X + Acc end, 0, [1,2,3]).   % 6
%%
%%   foldl is the general one. map and filter are special cases of it.
%%
%%   fun erlang:length/1                        % a named function as a value
%%   lists:map(fun integer_to_list/1, [1,2,3]). % ["1","2","3"]
%%
%% List comprehensions, which are often clearer than any of the above:
%%
%%   [X * 2 || X <- [1,2,3,4], X > 2].          % [6,8]
%%    ^output   ^generator      ^filter
%%
%%   [{X, Y} || X <- [1,2], Y <- [a,b]].        % every combination
%%   [X || {ok, X} <- Results].                 % a filter AND a
%%     destructure: entries that do not match {ok,_} are simply skipped,
%%     which makes this the idiomatic way to keep only the successes.

Discussion

No questions on this topic yet. Sign in to ask the first one.