[erlang-questions] "Symmetrical" function

Richard O'Keefe ok@REDACTED
Mon Feb 16 00:25:42 CET 2009


There are two approaches to the problem of
writing a symmetric function, depending on
what you think the problem is.

If the problem is WRITING every clause twice,
then don't.  Use the parse tools to take an
annotation such as
	-symmentric([{{f,2},{1,2}}]).
	% function f/2 is symmetric in arguments 1 and 2
and rewrite
	f(P11, P12) -> E1;
	...
	f(Pn1, Pn2) -> En.
to
	f(P12, P11) -> E1;
	f(P11, P12) -> E1;
	...
	f(Pn2, Pn1) -> En;
	f(Pn1, Pn2) -> En.

If the problem is HAVING two versions of each
clause, then

	f(X, Y) ->
	    try f'(X, Y)
	    catch your special exception ->
		try f'(Y, X) ->
		catch your special exception ->
		    fake a "no matching clause" exception
		end
	    end.

	f'(P11, P12) -> E1;
	...
	f'(Pn1, Pn2) -> En;
	f(_, _) -> throw your special exception.

Note that there is a behavioural difference:
the first version interleaves the swapped clauses with the
originals, while the second puts all the swapped clauses
after the originals.  The first approach can be modified
to get the effect of the second, but the second cannot
_easily_ be modified to get the effect of the first.




More information about the erlang-questions mailing list