[erlang-questions] Order of evaluation of guards

Richard A. O'Keefe ok@REDACTED
Tue Jan 6 05:20:26 CET 2015


On 5/01/2015, at 9:51 pm, Martin Koroudjiev <mrtndimitrov@REDACTED> wrote:

> Hello,
> 
> First of all - Happy New Year!
> 
> Suppose we have a function that accepts 2 integers and we want to react
> only when both integers are greater than 0 and one of them is less than 100:
> 
> I tried:
> (dilbert@REDACTED)1> F = fun(N, M) when N > 0, M > 0, N < 100; M < 100
> -> cool; (_, _) -> not_cool end.
> #Fun<erl_eval.12.106461118>
> (dilbert@REDACTED)2> F(1,2).
> cool
> (dilbert@REDACTED)3> F(1,200).
> cool
> (dilbert@REDACTED)4> F(0,200).
> not_cool
> (dilbert@REDACTED)5> F(0,50).
> cool
> 
> The last is not correct.

What do you mean, “not correct”?
You have defined:
   F(N, M) = if (N > 0 and N < 100 and M > 0) or M < 100 then cool else not_cool
In the call f(0, 50), 50 < 100, so the answer ‘cool’ is the only possible answer.

> What is the order of evaluation of the guards? Sadly parentheses are not
> allowed in guards.

It’s not clear to me what you mean by “order of evaluation” either.
The outcome here has nothing to do with the order in which things
are evaluated.

I _think_ you are talking about precedence, which is clearly spelled out in
the reference manual.  “;” (OR) has, as is traditional, wider scope than “,” (AND).

I have always found it inexplicable that Erlang does not allow the guard
combination operators “,” and “;” to be nested, with proper use of
parentheses when appropriate.  When “andalso” and “orelse” were allowed in
guards, the restriction became impossible to justify any longer.

If you want an “OR” to govern an “AND” you will have to use “andalso” instead
of “,” and “orelse” instead of “;”.




More information about the erlang-questions mailing list