Search code examples
haskellpattern-matchingcommutativity

Commutative Pattern Matching


I find it a little annoying to type

(+) 0 a = a
(+) a 0 = a
(*) 0 _ = 0
(*) _ 0 = 0
-- etc.

The following is more or less what I am trying to do

f [] a = a
f a [] = a
f (1:1:as) (1:1:1:bs) = [0,0] ++ (f as (0:bs))
f (1:1:1:as) (1:1:bs) = [0,0] ++ (f (0:as) bs)

Is there a way to state that a function is commutative? As in, is there a way to state that so long as any of the parameters are a particular value, then the result should be so-and-so?

I imagine it must be quite difficult, for the compiler-writers, to define such a behaviour, but I have already been surprised many times by haskell.

EDIT:

Thanks to the comments I have though of a way

f [] a = a
--f a [] = a
f (1:1:as) (1:1:1:bs) = [0,0] ++ (f as (0:bs))
--f (1:1:1:as) (1:1:bs) = [0,0] ++ (f (0:as) bs)
f a b = f b a

Though I imagine it must perform a little worse, since it has to check all the patterns, then flip then check again.


Solution

  • Thanks to the comments I have though of a way

    f [] a = a
    --f a [] = a
    f (1:1:as) (1:1:1:bs) = [0,0] ++ (f as (0:bs))
    --f (1:1:1:as) (1:1:bs) = [0,0] ++ (f (0:as) bs)
    f a b = f b a
    

    Though I imagine it must perform a little worse, since it has to check all the patterns, then flip then check again.