[erlang-questions] (newbie) Using Functions as Guards in Erlang

Thomas Lindgren thomasl_erlang@REDACTED
Fri Jun 13 15:00:56 CEST 2008


--- Jachym Holecek <jachym.holecek@REDACTED>
wrote:

> It could be useful and I admit I don't understand
> why is that prohibited  
> (besides
> "side effects and infinite loops in guards are Evil"
> to which one can  
> reply "the
> compiler can refuse a guard function if it can't
> prove it to be safe").

Arguably, that's already the case :-)

> Anyway,
> I'm not a compiler expert, so maybe there's a good
> reason I'm missing.

There are some potential compiler gains from having
easy-to-analyze guards (e.g., you can see whether
clauses are mutually exclusive more easily/often and
can easily reorder tests in guards), but I think this
restriction is mostly for historical reasons. Consider
that you can write arbitrary "guards" using standard
Erlang expressions, e.g.:

case catch (E1 andalso E2 andalso ... E3) of
   true -> Body;
   _ -> <next clause>
end

or even the useful

case catch abstype:is_abstype(X) of
   true -> Body;
   _ -> <next clause>
end

So, as far as I'm concerned, if you in practice end up
writing your complex tests using case instead of
guards, the guard syntax becomes less and less
relevant. Why hang on to such a restriction when it
just leads to more convoluted programs? Nowadays I'm
thus in favour of allowing arbitrary guards (possibly
disallowing side-effects by dynamic checking, but
perhaps I'm just reluctant to let go entirely :-).

Best,
Thomas

PS. The concurrent logic languages contemporary with
early Erlang in the 1980s also required flat guards,
but in those cases there was good reason to do so: it
was simply too hard to implement efficient arbitrary guards.


      



More information about the erlang-questions mailing list