Conditions: case and if

Erlang chooses between branches with two expressions. case matches a value against patterns, and if tests guard sequences. Both take the first branch that fits, both have no fall-through, and a value that no branch accepts is an error the program must expect. This lesson writes each form, then shows the error of a missing branch.

case of

case Value of tries its patterns in order; the first pattern that matches binds its variables and runs its body. The patterns are the ones of pattern matching, so a literal, a tuple or a bound variable all work:

erl

1> case 2 of 2> 1 -> one; 3> 2 -> two; 4> _ -> other 5> end. two 6> case {ok, 7} of 7> {ok, N} -> N * 2; 8> {error, _} -> 0 9> end. 14

The shell prompt counts continuation lines, so the whole expression is one query that ends at end.. A branch binds only inside its own body: the N of the first branch does not exist in the second.

Branches and bodies

A branch is a pattern, an arrow and one expression; semicolons separate branches and the last one has none. When the work of a branch needs more than one expression, wrap it in begin ... end or move it into a function. This module classifies an HTTP result with three clauses of a case, each fitting one shape:

http.erl

-module(http). -export([main/0, label/1]). label({ok, 200}) -> success; label({ok, Code}) -> {other, Code}; label({error, Reason}) -> {failed, Reason}. main() -> io:format("~p~n", [label({ok, 200})]), io:format("~p~n", [label({ok, 404})]), io:format("~p~n", [label({error, timeout})]).

erlc http.erl

erl -noshell -eval 'http:main(), halt().'

success {other,404} {failed,timeout}

The first clause is the specific case, the second catches every other ok and _Reason keeps the reason that the third returns. The order matters: {ok, 200} must come before {ok, Code}, or the general clause would swallow it.

When no branch matches

A case is not a chain of tests with a default: it has no default unless the page writes one. A value that fits no pattern stops the process with a case_clause error that carries the value:

erl

1> case 3 of 2> 1 -> one 3> end. ** exception error: no case clause matching 3

The error line is the whole report here: the shell prints the value that had no branch, which is often enough to see the missing shape. A program that must survive an unexpected value adds a final _ -> branch; a program that treats the value as a bug lets the process crash, and the supervisor restarts it. The error handling patterns lesson returns to that choice.

if

if has no patterns: every branch is a guard sequence, and the first one that evaluates to true runs. The comparison is the condition, as the no truthiness lesson explains. This module picks a sign with three guards:

sign.erl

-module(sign). -export([main/0, sign/1]). sign(Number) -> if Number > 0 -> positive; Number < 0 -> negative; true -> zero end. main() -> io:format("~p~n", [sign(5)]), io:format("~p~n", [sign(-5)]), io:format("~p~n", [sign(0)]).

erlc sign.erl

erl -noshell -eval 'sign:main(), halt().'

positive negative zero

The last branch is the guard true, which is the only catch-all an if has. It is a guard, not a pattern: _ would be a syntax error there.

The true branch

Without a true branch, an if whose guards all fail raises an if_clause error. The shell shows it in one line, again with no value to report because there was no value to test:

erl

1> if false -> yes end. ** exception error: no true branch found when evaluating an if expression

A function head with guards can often replace an if and reads better: one clause per condition, no nesting. This module grades a score that way, with the last clause as the catch-all:

grade.erl

-module(grade). -export([main/0, grade/1]). grade(Score) when Score >= 90 -> a; grade(Score) when Score >= 80 -> b; grade(Score) when Score >= 70 -> c; grade(_) -> f. main() -> io:format("~p~n", [grade(95)]), io:format("~p~n", [grade(85)]), io:format("~p~n", [grade(75)]), io:format("~p~n", [grade(50)]).

erlc grade.erl

erl -noshell -eval 'grade:main(), halt().'

a b c f

Use case when the shape of a value decides the branch and if when only a comparison does; use function clauses when the same choice is the whole function. The guards lesson lists what a guard may hold, and Functions and clauses shows the head form. The next lesson, Recursion replaces loops, uses both to repeat work without a loop.

Questions

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

  1. What does a case expression match its value against?

    Answer

    Patterns

    Each clause of a case is a pattern, and the first pattern that fits runs its body.

  2. How many branches of a case run for one value?

    Answer

    The first matching branch only

    The branches are tried in order, and the first match wins.

  3. What does this module print? -module(q4). -export([main/0]). main() -> Value = {error, timeout}, Result = case Value of {ok, _} -> ok; {error, Reason} -> {failed, Reason} end, io:format("~p~n", [Result]).

    Answer

    {failed,timeout}

    The second pattern matches, binds Reason to timeout, and the body returns {failed,timeout}.

  4. What does an if expression test?

    Answer

    Guard sequences

    if has no patterns: each branch is a guard, and the first guard that holds runs.

  5. What happens when no case branch matches?

    Answer

    A case_clause error is raised

    A failed match raises case_clause with the value that had no branch.

  6. What happens when no if guard holds?

    Answer

    An if_clause error is raised

    An if with no true guard raises if_clause, which is why the catch-all guard is true.

  7. Which guard is the usual catch-all in an if?

    Answer

    true

    A guard must be an expression, so the final branch uses the literal true rather than a pattern.

  8. What does this module print? -module(q1). -export([main/0]). main() -> Value = {ok, 7}, Result = case Value of {ok, N} -> N * 2; {error, _} -> 0 end, io:format("~p~n", [Result]).

    Answer

    14

    The tuple matches {ok, N} with N bound to 7, so the body returns 14.

  9. What does this module print? -module(q2). -export([main/0, sign/1]). sign(Number) -> if Number > 0 -> positive; Number < 0 -> negative; true -> zero end. main() -> io:format("~p~n", [sign(0)]).

    Answer

    zero

    Zero is neither greater nor less than zero, so the last guard answers zero.

  10. What does this module print? -module(q3). -export([main/0, grade/1]). grade(Score) when Score >= 90 -> a; grade(Score) when Score >= 70 -> b; grade(_) -> f. main() -> io:format("~p~n", [grade(85)]).

    Answer

    b

    85 fails the first guard and passes the second, so the answer is b.

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