Guards
What guards are
A guard is a boolean expression attached to a clause with when. The clause runs only when its pattern matches and its guard holds; otherwise matching moves to the next clause. The guard keeps the type tests and the range checks out of the body and puts them where a reader looks for the condition:
erl
1> case 5 of 2> N when N > 0 -> positive; 3> _ -> other 4> end. positive
A guard is a sequence of expressions, not a function body: it cannot assign a name, and it cannot call a function of your module. What it can call is the safe subset below.
Guard BIFs
A guard may call a built-in function from a fixed, safe list: the type tests (is_integer/1, is_atom/1, is_list/1, is_map/1 and the rest), length/1, map_size/1, element/2, hd/1, tl/1, abs/1, self/0 and the comparison operators. The restriction is the point: a guard must never fail or crash, so the runtime can test it cheaply. This module classifies any term with one type test per clause:
classify.erl
-module(classify). -export([main/0, classify/1]). classify(Number) when is_integer(Number) -> integer; classify(Atom) when is_atom(Atom) -> atom; classify(List) when is_list(List) -> list; classify(_) -> other. main() -> io:format("~p~n", [classify(5)]), io:format("~p~n", [classify(hello)]), io:format("~p~n", [classify([1, 2])]), io:format("~p~n", [classify({1, 2})]).
erlc classify.erl
erl -noshell -eval 'classify:main(), halt().'
integer atom list other
The order of the clauses is the order of the tests: a list is not an atom, and a tuple is none of the three, so it falls to the catch-all. The no truthiness lesson explains why each clause needs an explicit test rather than a bare value.
Guard sequences
Commas join tests into a sequence that must all hold, and semicolons split alternative sequences where any one may hold. Read the comma as and and the semicolon as or. This module uses both:
limit.erl
-module(limit). -export([main/0, limit/1]). limit(Number) when is_integer(Number), Number > 100 -> high; limit(Number) when is_integer(Number); is_float(Number) -> number; limit(_) -> other. main() -> io:format("~p~n", [limit(500)]), io:format("~p~n", [limit(50)]), io:format("~p~n", [limit(2.5)]), io:format("~p~n", [limit(atom)]).
erlc limit.erl
erl -noshell -eval 'limit:main(), halt().'
high number number other
The first clause needs both tests, the second needs either one, and the atom fits neither. The same comma and semicolon mean the same thing in an if, and the conditions lesson uses them there.
What guards cannot do
A guard cannot call a function of your own module, send a message or build new data. The compiler refuses the call and names the function and the place, so the mistake costs one build:
illegal.erl:4:11: call to local/imported function double/1 is illegal in guard is the whole message for a guard that calls a local helper. The fix is a guard BIF when one exists, or the helper call in the body after the clause has matched.
A guard that protects a call
The most common guard protects an operation that would crash on some input. A division by zero is an error, so the first clause states the condition under which the division is safe, and the second clause answers the zero:
safe_div.erl
-module(safe_div). -export([main/0, divide/2]). divide(A, B) when B =/= 0 -> {ok, A / B}; divide(_, 0) -> {error, div_by_zero}. main() -> io:format("~p~n", [divide(6, 3)]), io:format("~p~n", [divide(1, 0)]).
erlc safe_div.erl
erl -noshell -eval 'safe_div:main(), halt().'
{ok,2.0} {error,div_by_zero}
The guard is what keeps the first clause from running with a zero: a clause with a failing guard is skipped, not an error. The second clause then matches the zero explicitly, so the caller gets an error tuple instead of a crash, the same shape the tuples lesson introduced. A guard on hd/1 protects a list in the same way, and the error handling patterns lesson decides when to let the crash happen instead.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which keyword attaches a guard to a clause?
Answer
whenwhenseparates the head of a clause from its guard tests. -
What happens when a guard fails?
Answer
Matching moves to the next clause
A failed guard only rejects that clause; another clause may still match.
-
What does this module print?
-module(q4). -export([main/0, first/1]). first([Head | _]) when is_integer(Head) -> {ok, Head}; first(_) -> error. main() -> io:format("~p~n", [first([7, 8])]).Answer
{ok,7}The head is 7 and it is an integer, so the first clause matches and returns it.
-
What does a comma between guard tests mean?
Answer
And
All tests separated by commas must hold, as in
is_integer(N), N >= 90. -
What does a semicolon between guard tests mean?
Answer
Or
Semicolons separate alternatives, and any one of them may hold.
-
A guard calls a function of the same module. What does the compiler say?
Answer
call to local/imported function double/1 is illegal in guardOnly the safe guard BIFs may run in a guard, and the compiler names the illegal call.
-
Why is a guard allowed to call only a safe subset?
Answer
A guard must never fail or crash
The runtime tests guards cheaply and safely, so arbitrary calls are excluded.
-
What does this module print?
-module(q1). -export([main/0, classify/1]). classify(N) when is_integer(N) -> integer; classify(_) -> other. main() -> io:format("~p~n", [classify(hello)]).Answer
otherAn atom is not an integer, so the guard fails and the catch-all clause answers.
-
What does this module print?
-module(q2). -export([main/0]). limit(N) when is_integer(N), N > 100 -> high; limit(N) when is_integer(N) -> number; limit(_) -> other. main() -> io:format("~p~n", [limit(50)]).Answer
numberThe first clause needs a number above 100, so 50 reaches the second clause.
-
What does this module print?
-module(q3). -export([main/0]). divide(A, B) when B =/= 0 -> {ok, A / B}; divide(_, 0) -> {error, div_by_zero}. main() -> io:format("~p~n", [divide(1, 0)]).Answer
{error,div_by_zero}The guard rejects the zero for the first clause, so the second clause answers the error tuple.
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