[erlang-questions] Reading, Learning, Confused

Thomas Lindgren thomasl_erlang@REDACTED
Tue Jul 22 11:56:33 CEST 2008

--- On Tue, 7/22/08, Richard A. O'Keefe <ok@REDACTED> wrote:
> > 1. You can't nest ';', but you can nest
> orelse. This can be useful  
> > for macros and suchlike.
> (A) There is no reason whatever why ',' and
> ';' in guards COULDN'T
>      be allowed to nest.  That would have been the sensible
> thing
>      to do, rather than introducing new and confusing
> operators.

For what it's worth, I agree. But here we are.

> (B) I have yet to see any evidence that writing complicated
> guards
>      is a good idea.  If there are "macros and
> suchlike" that need
>      nested control operators in guards, PLEASE let us see
> some so
>      that we can tell whether there is a better way.

I already have a way that usually is better, which is to express a complex guard as an ordinary boolean-valued expression (perhaps even a new function) in a case. The price of this approach is that you don't get to use the more convenient guard syntax.

Here are the two broad classes of guard macros I have seen:

One case is when you want to hide representation.

  -define(is_equipment_foo(X), (record(X, eqm1) orelse record(X, eqm2)).

Another is when you refactor or name a commonly occurring test. Something like:

  -define(is_non_empty_list(X), (is_list(X) andalso X =/= [])).
  -define(is_byte(X), (X >= 0 andalso X =< 255)).

For concreteness, here are three guard macros from xmerl.hrl (R12B3):

%% whitespace consists of 'space', 'carriage return', 'line feed' or 'tab'
-define(whitespace(H), H==?space ; H==?cr ; H==?lf ; H==?tab).

%% non-caharacters according to Unicode: 16#ffff and 16#fffe
-define(non_character(H1,H2), H1==16#ff,H2==16#fe;H1==16#ff,H2==16#ff).

-define(non_ascii(H), list(H),hd(H)>=128;integer(H),H>=128).

I would guess these macros were written before the new guard operators, since they can only be used in specific contexts and would be more useful with andalso/orelse. But, mutatis mutandis, I think they are reasonable examples of what is done.

> > 2. I seem to recall that ';' is implemented by
> duplicating the  
> > clauses, while andalso/orelse is not. If so,
> andalso/orelse _may_  
> > yield somewhat more compact code.
> Ah, the old "I seem to recall" trick.

"Trick"? You got me, Richard. I always argue in bad faith.



More information about the erlang-questions mailing list