[erlang-questions] "Symmetrical" function

Michael Radford mrad-direct-erlang@REDACTED
Fri Feb 13 09:57:30 CET 2009


If the patterns are of some form where you can always determine from the
patterns alone when one of the two arguments is less than the other (and
if you don't care about integer vs. float), you can use the term order:

f (A, B) when A < B  -> f_ordered (A, B);
f (A, B) when A >= B -> f_ordered (B, A).

f_ordered (P1, P1) -> expr11;
f_ordered (P1, P2) -> expr12;
...

But that won't work for patterns like:
f ([_], [_,_]) -> 2;

In that case, you could first map each argument to an atom individually
using the same patterns, and then write the list of clauses in terms
of the atoms:

f (A, B) -> fp (p(A), p(B)).

fp (A, B) when A < B  -> fp_ordered (A, B);
fp (A, B) when A >= B -> fp_ordered (B, A).

p ([_])   -> p1;
p ([_,_]) -> p2;

fp_ordered (p1, p1) -> expr11;
fp_ordered (p1, p2) -> expr12;
...

Mike

Boris Okner writes:
> This must be a trivial question, and it's probably more related to  
> functional programming in general, rather then to Erlang.
> I have a function f(A,B) for which f(A,B) is ALWAYS equivalent to  
> f(B,A).  So I call it "symmetrical".
> Arguments A and B  are patterns, and f is legal for some of  
> combinations of A and B.
> So I have a (long) list of clauses like so:
> f(P1, P1) -> expr11;
> f(P1, P2) -> expr12;
> f(P1, P3) -> expr13;
> f(P2, P3) -> expr23;
> .......
> f(Pm, Pn) -> expr_m_n;
> 
> %Other pairs are illegal
> f(_, _) ->throw(illegalPairException).
> 
> My problem that I don't want to manually write  clauses like f(P2,  
> P1), f(P3, P1) etc., because symmetrical cases would have been already  
> described (i.e. f(P1, P2) is equivalent to f(P2,P1)).
> And I can't use
> f(A, B) -> f(B,A)
> because "illegal"  clause already covers this case.
> 
> Thank you for suggestions!
> 
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions



More information about the erlang-questions mailing list