Erlang Guards

Erlang Variables

Guard structures

Guards in Erlang are boolean functions placed after the key word, “when” and before the arrow, “->”. Guards may appear as part of a function definition, ‘receive’, ‘if’, ‘case’ and ‘try/catch’ expressions.

We use a guard in a function definition.

Example:

example.erl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
-module(example).
-compile(export_all).

the_answer_is(N) when N =:= 42 -> true;
the_answer_is(N) -> false.

% c(example).
% ok
%
% example:the_answer_is(42).
% true
%
% example:the_answer_is(21).
% false

fun definition

1
2
3
4
F = fun
  (N) when N =:= 42 -> true;
  (N) -> false
end.

receive expression

1
2
3
4
receive
  {answer, N} when N =:= 42 -> true;
  {answer, N} -> false
end.

if expression

1
2
3
4
if
  N =:= 42 -> true;
  true -> false
end.

case expression

1
2
3
4
case L of
  {answer, N} when N =:= 42 -> true;
  _ -> false
end.
1
2
3
4
case L of
  {node, N} when N =:= 42 -> true;
  _AnyNode -> false
end.

try/catch

1
2
3
4
5
6
7
8
try find(L) of
  {answer, N} when N =:= 42 -> true;
  _ -> false
catch
  {notanumber, R} when is_list(R) -> alist;
  {notanumber, R} when is_float(R) -> afloat
  _ -> noidea
end.

Multiple Guards

It is possible to use multiple guards within the same function definition or expression. When using multiple guards, a semicolon, “;”, signifies a boolean “OR”, while a comma, “,”, signifies boolean “AND”.

Example:

1
2
the_answer_is(N) when N == 42, is_integer(N) -> true;
geq_1_or_leq_2(N) when N >= 1; N =< 2 -> true;

Guard Functions

There are several built-in-functions which be used in a guard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
is_alive/0
is_boolean/1
is_builtin/3
is_constant/1
is_float/1
is_function/2
is_function/1
is_integer/1
is_list/1
is_number/1
is_pid/1
is_port/1
is_record/3
is_record/2
is_reference/1
is_tuple/1

tuple_size/1
is_binary/1
is_bitstring/1
bit_size/1
byte_size/1
length(Z) > N
1
2
3
4
5
6
7
8
A > B
A < B
A == B
A =< B
A >= B
A /= B
A =:= B
A =/= B