[erlang-questions] A matter of style?

Björn Gustavsson <>
Sat Aug 14 09:18:57 CEST 2010


On Fri, Aug 13, 2010 at 5:11 PM, Iñaki Garay <> wrote:
> within(X, Y, Z, Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) ->
>    (Xmin =< X) and
>    (X =< Xmax) and
>    (Ymin =< Y) and
>    (Y =< Ymax) and
>    (Zmin =< Z) and
>    (Z =< Zmax).

Written like this, all conditions will be evaluated every time,
even if a condition has evaluated to false.

To ensure that the function returns false as soon as one
condition evaluates to false, rewrite it like this:

within(X, Y, Z, Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) ->
   Xmin =< X andalso
   X =< Xmax andalso
   Ymin =< Y andalso
   Y =< Ymax andalso
   Zmin =< Z andalso
   Z =< Zmax.

Alternately, it can be written like this:

within(X, Y, Z, Xmin, Ymin, Zmin, Xmax, Ymax, Zmax) when
Xmin =< X, X =< Xmax, Ymin =< Y,
Y =< Ymax, Zmin =< Z, Z =< Zmax ->
    true;
within(_, _, _, _, _, _, _, _, _) ->
    false.

In general, boolean expressions in guards will
be short-circuited unless that would break
the semantics. For instance, in this function

f(A, B) when (length(A) > 5) or (length(B) > 10) ->
    ok.

both length(A) and length(B) will always be
evaluated.

-- 
Björn Gustavsson, Erlang/OTP, Ericsson AB


More information about the erlang-questions mailing list