[erlang-questions] style question - best way to test multiple non-guard conditions sequentially
Fri Jun 21 00:07:46 CEST 2013
I don't believe they do in places where guards are the only inhabitant.
I do believe they violate it in comprehensions; call these two functions with [foo]:
F = fun (L) -> [ X || X <- L, X rem 2 =:= 0 ],
G = fun (L) -> [ X || X <- L, _ = X rem 2 =:= 0 ].
PS: Sorry for the double mail Jonathan, failed to reply to all.
Le 20 juin 2013 à 19:33, Jonathan Leivent a écrit :
>> 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
> erlang-questions mailing list
More information about the erlang-questions