[erlang-questions] "Symmetrical" function

Richard O'Keefe ok@REDACTED
Tue Feb 17 05:05:10 CET 2009

On 17 Feb 2009, at 11:56 am, Michael Radford wrote:
> (The original poster was rather emphatic: "I have a function f(A,B)  
> for
> which f(A,B) is ALWAYS equivalent to f(B,A)".)

That is, the *abstract* function he wanted to implement is symmetric,
but he wanted to know how to halve the work of writing it.

> Actually, that assumption was unnecessary.

Whether that is so depends on how the function is to be implemented.
As several people pointed out, sometimes the answer is

	f(X, Y) when X =< Y -> f1(X, Y);
	f(X, Y)             -> f1(Y, X).

If the f1 clauses are a mix of choices from both sides of the
main diagonal of the matrix, that won't work.

Some obvious questions are "for the intended symmetric f : A x A -> B,
what is #A?  And how many clauses would you have for the implemented
f without using any trickery?  Why do you think it is feasible to
write half of the function?"

Let's take the intersection of two sorted lists as an example
of a symmetric function:

	oi([X|Xs], [Y|Ys]) ->
	    if X < Y -> oi(Xs, [Y|Ys])
	     ; X > Y -> oi([X|Xs], Ys)
	     ; true  -> oi(Xs, Ys)
	oi(_, _) ->

Here #A is infinite, the number of clauses is 2, and I don't see
any good way to write half of f.

More information about the erlang-questions mailing list