8.14 Short-Circuit Expressions
8.14 Short-Circuit Expressions
Expr1 orelse Expr2
Expr1 andalso Expr2
Expr2 is evaluated only if necessary. That is, Expr2 is evaluated only if:
- Expr1 evaluates to false in an orelse expression.
or
- Expr1 evaluates to true in an andalso expression.
Returns either the value of Expr1 (that is, true or false) or the value of Expr2 (if Expr2 is evaluated).
Example 1:
case A >= -1.0 andalso math:sqrt(A+1) > B of
This works even if A is less than -1.0, since in that case, math:sqrt/1 is never evaluated.
Example 2:
OnlyOne = is_atom(L) orelse
(is_list(L) andalso length(L) == 1),
From Erlang/OTP R13A, Expr2 is no longer required to evaluate to a Boolean value. As a consequence, andalso and orelse are now tail-recursive. For instance, the following function is tail-recursive in Erlang/OTP R13A and later:
all(Pred, [Hd|Tail]) ->
Pred(Hd) andalso all(Pred, Tail);
all(_, []) ->
true.
