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

Fuad Tabba fuad@REDACTED
Mon Jun 16 00:33:40 CEST 2008


Thanks for everyone for your responses. They were definitely helpful, I now
understand Erlang and some of these issues a bit better.

I ended up using macros (as Gleb and Robert suggested; specifically the
macro Gleb posted). I think this is a more elegant solution than doing any
other transformations of the code, but I could be wrong...

Anyway, I uploaded my code to:-
http://www.cs.auckland.ac.nz/~fuad/rbtree.erl<http://www.cs.auckland.ac.nz/%7Efuad/rbtree.erl>
http://www.altabba.org/2008/06/full-red-black-tree-implementation-in.html(for
some background)

If anyone has any comments about my code I would appreciate it.

Robert: I've based my delete algorithm on the one at
http://sage.mc.yu.edu/kbeen/teaching/algorithms/resources/red-black-tree.html,
would definitely be interested in a faster algorithm. Is it the one
you're
using for the rbdict you posted?

Thanks again.

Cheers,
/Fuad

On Sun, Jun 15, 2008 at 2:26 AM, Robert Virding <rvirding@REDACTED> wrote:

> 2008/6/13 Fuad Tabba <fuad@REDACTED>:
>
>> 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/20080616/b7a7ee0e/attachment.htm>


More information about the erlang-questions mailing list