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

Fuad Tabba fuad@REDACTED
Fri Jun 13 06:06:25 CEST 2008


Hi,

I'm new to Erlang, so I apologize in advance for asking what might be
obvious to some.

I've run into problem trying to use functions as guards in Erlang. I looked
through the manual, and discovered that this isn't allowed by the language
in case those functions have side-effects. The thing is, my functions do not
have side effects. Is there a way to convey that message to the compiler and
allow my functions to be used as guards? (Something along the lines of
#pragma i_swear_this_function_has_no_side_effects).

I know that code can be rewritten to avoid this problem, however, and
probably due to my limited experience with Erlang, the particular piece of
code I have in mind would look really ugly and really complicated without
the ability to do this. Below is a snippet of my code that I'm referring to,
if anyone has any suggestions on how to make it work in Erlang and look
elegant I'd appreciate it.

This code deals with fixing up a red black tree after a node has been
deleted, and here's what I'm trying to do:-

% Algorithm from
http://sage.mc.yu.edu/kbeen/teaching/algorithms/resources/red-black-tree.html

% Case B1
delfix({Ky, Vy, Cy, {Kx, Vx, bb, A, B}, {Kz, Vz, b, C, D}}) when (isBlack(C)
and isBlack(D)) ->
     blackToken({Ky, Vy, Cy, {Kx, Vx, b, A, B}, {Kz, Vz, r, C, D}});

% Above is one of many clauses for the delfix function. Below is the full
isBlack function:-

% An empty node (or subtree) or a black node (or subtree) are black (true),
everything else is red (false).
isBlack({}) -> true;
isBlack({_, b, _, _, _}) -> true;
isBlack(_) -> false.

Now, rewriting the code for delfix as an if-statement wouldn't work without
modifying a bunch of other things, because if C or D aren't black, there are
other different patterns (not shown above) that might match. Expanding the
tuples C and the D into something along the lines of {Kc, Vc, b, Lc, Rc} to
match looks ugly, and would ignore the case where either might be empty
subtrees {}.

I hope that my question actually makes sense :) If you've come this far in
the email then thanks for bearing with me and my long, newbie question.

On a side node, I tried to create an account at the trapexit forum; but once
I reach the page after agreeing to the conditions of the forums I get a huge
SQL error message - something is wrong with the whole registration
mechanism....

Cheers,
/Fuad
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20080613/52ff7ed9/attachment.htm>


More information about the erlang-questions mailing list