Truthiness: only false and nil
| Only two false values | |
| Short-circuit and | |
| In guards | |
| Type checks |
Only two false values
In Erlang exactly two values count as false: the atom false and the empty list nil. Everything else is true, including zero and the empty binary.
This is stricter than most languages, so conditions never trip over a zero by accident.
0.
0
2> is_atom([]).
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.
X = nil, X =/= nil 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.
case [] of
[] -> empty;
_ -> nonempty
end.
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.
is_integer(42).
true
2> is_binary("text").
true
Next: Conditions: case and if
Article author: Arthur Isaev