[erlang-questions] style question - best way to test multiple non-guard conditions sequentially

Jonathan Leivent jleivent@REDACTED
Thu Jun 20 19:33:11 CEST 2013


> OK - that is surprising.  That certainly changes my thinking about if
> statements.  Is this particular semantic difference between guards and
> general conditions ever expressed in the reference manual?  If so, I
> certainly missed it.

On closer inspection:

"If an arithmetic expression, a boolean expression, a short-circuit 
expression, or a call to a guard BIF fails (because of invalid 
arguments), the entire guard fails. "

Before understanding this semantic peculiarity of guards, the 
parenthetical portion of the above statement in the reference manual 
didn't make much of an impression on me.  Now, I see it is conveying 
this semantics.  Actually, when I read that sentence alone, it still 
doesn't quite do the trick.  It's the following sentence:

"If the guard was part of a guard sequence, the next guard in the 
sequence (that is, the guard following the next semicolon) will be 
evaluated."

that completes the meaning by disambiguating "fails" as "evaluates to 
false" instead of "throws an exception".  Although, still, I'd probably 
make the mistake of typing "length(0)." into the interpreter, seeing the 
error, and think that this experience overrules what I might have 
otherwise inferred from the manual.  To further confuse matters (or, 
maybe just me), many guards are is_type tests - which would seem to be 
useful, but are not, as protection for other guards in the same guard 
expression:

   if is_list(X), length(X) =:= 3 -> ...

Previous to this discussion, the reference manual statement: "The reason 
for restricting the set of valid expressions is that evaluation of a 
guard expression must be guaranteed to be free of side effects." was the 
one that I based my (mis)understanding of the guard/condition 
distinction on.  I could understand why that would be an important 
restriction for guards on things like function and receive clauses, but 
not so much on if statements - or, at least, why there would not be any 
Erlang statement that would allow testing a sequence of arbitrary 
conditions.

Doesn't guard semantics violate the Principle of Least Astonishment?

I'd be astonished if I was alone in thinking that...

-- Jonathan




More information about the erlang-questions mailing list