[erlang-questions] difference between ", " and "andalso" in guards

Richard A. O'Keefe ok@REDACTED
Mon May 19 01:02:00 CEST 2014

On 18/05/2014, at 4:20 PM, Adel Zhang wrote:

> hi, I am currently reading "learnyousomeerlang". In "Syntax in Functions" chapter "guards" section, Fred said
> <quote>
> Note: I've compared , and ; in guards to the operators andalso and orelse. They're not exactly the same, though. The former pair will catch exceptions as they happen while the latter won't.

This is seriously misleading.

The difference between  X > Y , X < Z
and X > Y andalso X < Z
with respect to exceptions has NOTHING TO DO with whether
it's comma or andalso.  The right semantic model is that
it is the tests X > Y and X < Z themselves which change.
If a guard test would have raised an exception, that
turns into a simple failure of the guard test.


1> F1 = fun (X) when X+1 > 2 -> ok ; (_) -> oops end.
2> F2 = fun (X) -> B = (X + 1 > 2), if B -> ok ; true -> oops end end.
3> F1(snark).
4> F2(snark).
** exited: {badarith,...} **

This being so, "," never gets to *see* an exception,
so how could it catch one?

You can't verify Fred's statement, because it isn't true.
"," and ";" no more catch exceptions than "->" does.

More information about the erlang-questions mailing list