How overload operator in Haskell?

Ashley Yakeley ashley@semantic.org
Thu, 10 Jul 2003 23:16:56 -0700


In article <20030710005851.GA1068@smtp.alicorna.com>,
 Andrew J Bromage <ajb@spamcop.net> wrote:

> This suggests that wrapping each "standard" mathemtaical
> function/operator in its own typeclass would have literally
> no run-time performance penalty:
> 
> 	class Plus a b c | a b -> c where
> 	    (+) :: a -> b -> c
> 
> 	class Mult a b c | a b -> c where
> 	    (*) :: a -> b -> c

As written, this is _not_ a good idea. Trust me, you end up having to 
put type annotations everywhere. Even (3 + 4 :: Integer) is ambiguous, 
you have to write (3 :: Integer) + (4 :: Integer).

In HBase, I do this:

    class Additive a b ab | a b -> ab where
      add :: a -> b -> ab;

    infixl 6 +;
    (+) :: (Additive a a a) => a -> a -> a;
    b + a = add a b;

    etc.

The arguments are swapped because I read "subtract 1 a" and "a - 1" both 
as "subtract 1 from a", etc. Perhaps one could get away with this:

    (+) :: (Additive a b a) => a -> b -> a;

-- 
Ashley Yakeley, Seattle WA