[erlang-questions] "Symmetrical" function

Andras Georgy Bekes bekesa@REDACTED
Fri Feb 13 14:00:04 CET 2009


> Maybe try this one:
>
> f(P1, P2) when P1 > P2 ->
>   f1(P1, P2);
> f(P1, P2) ->
>   f1(P2, P1).
Bad idea. Comparing might take very long time! With this you can convert 
a function with runtime proportional to pattern size to a function with 
runtime proportional to parameter size.

Try this:
N=10000000, lists:seq(1,N) > lists:seq(1,N+1).

It will also block the whole VM (one scheduler) for an arbitary time. 
See 
http://www.erlang.org/pipermail/erlang-questions/2008-March/033838.html
Note that term comparisons like > are BIFs, just like '--'.

I think the right solution for the problem is using macros:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-define(fSYM(P1,P2,Result),
	f(P1,P2)->Result;
	f(P2,P1)->Result
       ).

% XOR function
?fSYM(0,1,1);
f(X,X)->0.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Of course you can parametrise the macro with the function name as well.

	Georgy



More information about the erlang-questions mailing list