[erlang-questions] guard subexpressions resulting in a runtime error

ok <>
Sun Jul 22 13:10:26 CEST 2012

> $ erl -v
> Erlang R15B01 (erts-5.9.1) [source] [smp:2:2] [async-threads:0] [hipe]
> [kernel-poll:false]
> According to "Erlang Programming" p.51,
> "Guard subexpressions resulting in a runtime error are treated as
> returning false"

> But with this function definition:
> guard1(N) when ((N/0 == 0) or N==1) ->
>   hello.

This is a perfect example of why it was EVIL to allow
Boolean operators in guards instead of sticking with
, and ;.

If this were guard1(N) when N/0 == 0 ; N == 1 -> hello.
it would do what you expected.

1> F = fun (N) when N/0 == 0 ; N == 1 -> hello end.
2> F(1).

But 'or' is a plain old operator that evaluates both
of its arguments, and when one of its operands erred,
the *whole* guard expression failed.  You had only
one guard, so when it failed, there was nothing left
to test.  Using 'orelse' doesn't help either:
    N/0 == 0 orelse N == 1
is still ONE expression, so ONE guard test, and if
any part of it errs, the whole of it fails.

This is a straightforward inference from the documentation
if you are familiar with the Good Old Ways and expect
these new-fangled operators to do something stupid, but if
you are a trusting soul who isn't aware that Boolean
operators belong to the Holocene period of Erlang, it
would be helpful if the Erlang manual were a bit more
explicit about this.

More information about the erlang-questions mailing list