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

Robert Virding <>
Sat Jun 14 16:26:18 CEST 2008


2008/6/13 Fuad Tabba <>:

> Thanks Doug and Jachym.
>
> Jachym is right, Doug's suggestion would work if the guard was inside my
> function rather than at a top level context. I know that I could rewrite my
> code and convert it to a bunch of if statements, but I can't think of a way
> to write such code without it looking ugly.
>
> Being able to use a function with a guard seems like it would be the most
> elegant solution.
>

It would open a can of worms that I would rather see remain closed,
specifically side effects and message passing. Just being able to declare
something as "guard safe" wouldn't really help as the system would still
have to be able to do something sensible in all cases. Otherswise you would
be surprised what users can dream up. "It's hard to make a program foolproof
because fools are so ingenious".

Any suggestions?


I used the following macros for just that case:

%% {r,Left,Key,Val,Right}
%% {b,Left,Key,Val,Right}
%% empty

-define(IS_RED(N), (is_tuple(N) andalso element(1, N) == r)).
%% -define(IS_BLACK(N), not (is_tuple(N) andalso element(1, N) == r)).
-define(IS_BLACK(N),
    ((is_tuple(N) andalso (element(1, N) == b)) orelse (N == empty))).

These are guard safe and usable on the rhs as well. If they are the most
efficient I don't know.

I have also found another algorithm for deleting if you are interested which
is a little faster. At least in my implementation. Deleting in RB-trees is
not trivial.

Robert
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080614/998991f1/attachment.html>


More information about the erlang-questions mailing list