# Old style vs. new style boolean expressions

Håkan Stenholm hakan.stenholm@REDACTED
Tue Oct 8 21:57:16 CEST 2002


 >Here is a function written in classic Erlang style:
 >
 >is_alphanum(N) when N >= $A, N =< $Z -> true;
 >is_alphanum(N) when N >= $a, N =< $z -> true;
 >is_alphanum(N) when N >= $0, N =< $9 -> true;
 >is_alphanum($_) -> true;
 >is_alphanum(_) -> false.

In R8 this can also be written as:

 >is_alphanum(N) when N >= $A and N =< $Z -> true;
 >is_alphanum(N) when N >= $a and N =< $z -> true;
 >is_alphanum(N) when N >= $0 and N =< $9 -> true;
 >is_alphanum($_) -> true;
 >is_alphanum(_) -> false.
 >
 >This can also be written using boolean expression guards, which were
 >introduced in (I think) R8:
 >
 >is_alphanum(N) ->
 >    ((N >= $A) and (N =< $Z)) or
 >    ((N >= $a) and (N =< $z)) or
 >    ((N >= $0) and (N =< $9)) or
 >    (N == $_).


Im fairly sure this has been available since R5 (possibly undocumented),
the 'andalso' and 'orelse' below on the other hand are from R8.

 >
 >This isn't as efficient as the first method, because the boolean 
expression
 >in the second code snippet is always fully evaluated.  To fix this, use
 >"andalso" and "orelse":
 >
 >is_alphanum(N) ->
 >    ((N >= $A) andalso (N =< $Z)) orelse
 >    ((N >= $a) andalso (N =< $z)) orelse
 >    ((N >= $0) andalso (N =< $9)) orelse
 >    (N == $_).
 >
 >Now the point:  The first vesion generates by far the smallest beam file,
 >the second is somewhat larger, and the third is still larger.  When 
fiddling
 >with a module containing many similar functions, switching from first 
to the
 >third method increased the beam file size by 40%.

I don't think this make much of a difference most of the time, and even 
if it
increases the size noticeably - does it matter ?

 >
 >Is this just because boolean expressions are a relatively new 
addition, and
 >so the R8 compiler doesn't deal with them well, or is it deeper than that?
 >
 >I'm still not sure whether I think the first or third method is cleaner :)



I think I like the first version is best (in this case), it's fairly clear
that N is checked to see if it belongs to a certain char range as well 
as what
is returned if the match is true/false.
I think the main difference is that the first version only requires you to
comprehend the meaning of one simple match at a time, while the later 
versions
require you to comprehend one big boolean expression all at once.




More information about the erlang-questions mailing list