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

Gleb Peregud <>
Fri Jun 13 12:34:14 CEST 2008


2008/6/13 Fuad Tabba <>:
> 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?
>
> ...
>
> % 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.

You may use macros:

-define(is_black(X), ((X =:= {}) orelse (element(2, X) =:= b))).

and

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

I didn't checked this, but it may work

Best regards,
-- 
Gleb Peregud
http://gleber.pl/

Every minute is to be grasped.
Time waits for nobody.
-- Inscription on a Zen Gong



More information about the erlang-questions mailing list