Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Functions and Pattern Matching

case, if and Guards

Choose between branches in Erlang with case, if and guard sequences. Learn which functions are allowed in guards, how guards fail safely and when to use each form.

Erlang has no else if chains and no ternary operator. For decisions you use pattern matching in function heads, the case expression, the if expression and guards: extra conditions attached to a clause. This lesson shows when each is the right tool.

The case expression

case matches a value against patterns, in order:

ERLANG
-module(traffic).
-export([action/1]).

action(Light) ->
    case Light of
        green  -> go;
        yellow -> slow_down;
        red    -> stop;
        Other  -> {unknown, Other}
    end.

Each branch is Pattern -> Body, branches are separated by semicolons, and the last one has no semicolon before end. The whole case is an expression whose value is the body of the matched branch. If nothing matches, the process crashes with a case_clause error, which is exactly what happens in a function without a matching clause.

You can match structures and bind variables:

ERLANG
handle(Result) ->
    case Result of
        {ok, Value} -> {done, Value * 2};
        {error, not_found} -> {done, 0};
        {error, Reason} -> {failed, Reason}
    end.

Guards

A guard is a boolean test after the keyword when. The clause is used only if the pattern matches and the guard is true.

ERLANG
classify(N) when N < 0 -> negative;
classify(0) -> zero;
classify(N) when N > 0, N < 10 -> small;
classify(N) when N >= 10 -> large.

Guards work in function heads, case branches, receive and funs:

ERLANG
case Age of
    A when A < 13 -> child;
    A when A < 20 -> teenager;
    _ -> adult
end

Combining guard tests

  • A comma means and: when X > 0, X < 10.
  • A semicolon means or: when X < 0; X > 100.
  • Both can be combined: when A > 0, B > 0; C > 0 is (A > 0 and B > 0) or C > 0.

You can use andalso and orelse in guards too, but commas and semicolons are the idiom. If a guard raises an error (for example a comparison on the wrong type), the guard simply fails and the next clause is tried. Errors never escape from a guard.

What is allowed in guards

Guards must be free of side effects, so only a fixed set of functions and operators is permitted:

  • Type tests: is_atom/1, is_integer/1, is_float/1, is_number/1, is_list/1, is_tuple/1, is_map/1, is_binary/1, is_boolean/1, is_pid/1, is_function/1.
  • Comparison and arithmetic operators, andalso, orelse, not.
  • Selected built-ins: length/1, hd/1, tl/1, abs/1, element/2, size/1, tuple_size/1, byte_size/1, map_size/1, map_get/2, is_map_key/2, max/2, min/2, round/1, trunc/1, node/0, self/0.

You cannot call your own functions in a guard, nor functions like lists:member/2. If you need that, compute the value first and test it in a case.

ERLANG
first_even([X | _]) when is_integer(X), X rem 2 =:= 0 -> {ok, X};
first_even(_) -> none.

The if expression

if is just a list of guards with no pattern. The first guard that is true wins:

ERLANG
sign(N) ->
    if
        N > 0 -> positive;
        N < 0 -> negative;
        true  -> zero
    end.

The final true acts as an else. If no guard is true and there is no true branch, you get an if_clause error. Because only guard tests are allowed in if, you cannot call arbitrary functions in it, which is why most programmers choose case or function clauses instead.

Choosing between them

flowchart TD
    A["Need to decide?"] --> B{"Depends on the shape of the data?"}
    B -- "yes" --> C["Function clauses or case"]
    B -- "no" --> D{"Only simple tests on values?"}
    D -- "yes" --> E["Guards or if"]
    D -- "no" --> F["Compute first, then case on the result"]

A rough decision guide. Pattern matching first, guards to refine it.

As a rule of thumb: pattern matching in clause heads is the most readable. Add guards only for what a pattern cannot say (ranges, type checks). Use case to branch on the result of a call. Use if rarely.

Branching on the result of a function

ERLANG
safe_div(_, 0) -> {error, division_by_zero};
safe_div(A, B) -> {ok, A / B}.

report(A, B) ->
    case safe_div(A, B) of
        {ok, Q} -> io:format("~p~n", [Q]);
        {error, Why} -> io:format("error: ~p~n", [Why])
    end.

Here the function with two clauses does one job, and case consumes its result.

Stand-ins in JavaScript

These imitate case with guards and if as a list of tests. They are not Erlang.

JS Stand-in: case with guards (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: if with a final true (JavaScript, not Erlang)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a comma between two guard tests mean?

    Commas mean and; semicolons mean or.
  2. 2. What happens if a guard test raises an error?

    Errors in guards are swallowed: the guard simply fails.
  3. 3. Which is NOT allowed in a guard?

    Guards may only call a fixed set of side-effect free built-ins, not general library functions.
  4. 4. What error does an if with no true guard raise?

    If no guard succeeds, the expression fails with if_clause. A final true branch acts as else.

Summary

  • case Expr of Pattern -> Body; ... end branches on the shape of a value and returns the matching body.
  • Guards (when) add conditions; , is and, ; is or, and errors in guards just fail them.
  • Only a restricted set of built-ins is allowed in guards.
  • if has only guards; end it with true -> for a default.
  • Prefer clause heads, then guards, then case; use if sparingly.

Next: Recursion and Tail Calls