[Haskell-cafe] class question
Hans van Thiel
hthiel.char at zonnet.nl
Sun Jan 21 14:00:53 EST 2007
On Sun, 2007-01-21 at 09:42 -0800, Stefan O'Rear wrote:
> On Sun, Jan 21, 2007 at 06:21:34PM +0100, Hans van Thiel wrote:
> > class (Num a, Monoid a) => NumMon a where
> > e = 0
> > add x y = x + y
>
> > What am I doing wrong? Many thanks in advance.
>
> Nothing!
>
> What you are trying to do, declare a class B containing all members
> of a class A, is simply not supported in Haskell.
>
> This is the closest you'll get with Haskell98:
>
> > newtype Wrap a = Wrap (Wrap a)
> > instance Num a => Monoid (Wrap a) where
> > e = Wrap 0
> > add (Wrap x) (Wrap y) = Wrap (x + y)
>
> This is the closest you'll get with GHC extensions:
>
> > {-# OPTIONS_GHC -fallow-undecidable-instances #-}
> > instance Num a => Monoid a where
> > e = 0
> > add = (+)
>
>
> Hope this helps.
Yes, thank you. The one with the gHC extension looks like what I wanted
to do, but then in reverse order, declare the numbers to be monoids.
Expanding on this, I've now got:
class Monoid a => Group a where
inv :: a -> a
minus :: a-> a -> a
minus x y = add x (inv y)
inv x = minus e x
instance Group Int where
minus = flip subtract
-- inv x = -x
This seems to work. What I like is that, like in EQ and Ord, functions
are defined in several ways by default. So, for Int, you can choose to
define either inv or minus, you don't have to do both.
But subtract and - are defined over all types of Num, so it would be
nice to have something like
instance Group a => Num a where .....
I understand this cannot be done in Haskell98, but it can with the GHC
extension? Does {-# OPTIONS_GHC -fallow-undecidable-instances #-} refer
to possibly infinite definitions? Thanks again!
Hans van Thiel
More information about the Haskell-Cafe
mailing list