8.14 Short-Circuit Expressions

  1. Expr1 orelse Expr2
  2. 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:

  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:

  1. OnlyOne = is_atom(L) orelse
  2. (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:

  1. all(Pred, [Hd|Tail]) ->
  2. Pred(Hd) andalso all(Pred, Tail);
  3. all(_, []) ->
  4. true.