Truthiness: only false and nil
Only two false values
In Erlang exactly two values count as false: the atom false and the empty list []. Everything else is true, including zero, nil, and the empty binary.
This is stricter than most languages, so conditions never trip over a zero by accident.
erl
1> 0.
0
2> is_list([]).
true
Short-circuit and
andalso and orelse are the short-circuit forms. The right side runs only when the left side cannot decide the answer.
Use them to guard access, just like the and and or of other languages.
erl
1> X = [], X =/= [] andalso X > 0.
false
2> true orelse error(boom).
true
In guards
Guard expressions in case and if see the same truthiness. A guard sequence succeeds when its last test holds.
Lesson 17 covers guards in full, including which functions may appear inside one.
erl
1> case [] of
2> [] -> empty;
3> _ -> nonempty
4> end.
empty
Type checks
The is functions answer type questions: is_atom, is_integer, is_binary, and the rest of the family. They are the honest way to test a value.
Pair them with the comparison operators of lesson 7 and every branch of your code states exactly what it expects.
erl
1> is_integer(42).
true
2> is_binary(<<"text">>).
true
Next: Conditions: case and if
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which two values are false in Erlang?
Answer
falseand[]Only the atom
falseand the empty list[]count as false; every other term is true, includingnil. -
Is the number
0true or false in a condition?Answer
True, because only two values are false
Zero is an ordinary term, and only
falseandnilare false. -
What does
is_list([]).return?Answer
trueThe empty list is still a list, so the type test holds.
-
What does
true orelse error(boom).return?Answer
trueorelsestops as soon as the left side is true, so the failing right side never runs. -
What does
false andalso error(boom).do?Answer
Returns
falsewithout callingerror/1andalsoskips the right side when the left side is false, which is the point of the short-circuit form. -
What does
X = [], X =/= [] andalso X > 0.return?Answer
falseXbecomes[], soX =/= []is false and the rest of the expression is skipped. -
Which function tests for a whole number?
Answer
is_integer/1is_integer/1answers true for integers only;is_number/1also accepts floats. -
What does
is_binary(<<"text">>).return?Answer
trueThe value is a binary, so the type test holds.
-
Why is
andalsosafer thanandfor a guarded access?Answer
It skips the right side when the left side decides
The short-circuit form never evaluates the right side when the left side is already false.
-
What does the
case [] ofexample return?Answer
emptyThe value
[]matches the first pattern, so the bodyemptyis returned.
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.
Article author: Arthur Isaev