[Haskell-beginners] Tyepclasses and creating 'Num' instances

Stuart Hungerford stuart.hungerford at gmail.com
Mon Feb 23 20:46:56 UTC 2015


Hi,

Many thanks to everyone who responded to my earlier question about
hierarchies of typeclasses. I have a followup question regarding
creating instances.  Suppose I have this additive semigroup typeclass:

class (Num a) => AddSemigroup a where
  (|+|) :: a -> a -> a
  (|+|) = (+)

I'd like to make 2-element tuples instances of AddSemigroup, provided
their elements are:

instance (AddSemigroup a, AddSemigroup b) => AddSemigroup (a, b)

GHC says it "Could not deduce (Num (a, b))" in this situation, which
seems fair enough so I tried:

instance (AddSemigroup a, Num a, AddSemigroup b, Num b) => AddSemigroup (a, b)

With the same result.  Separate instances seem to work though:

instance (Num a, Num b) => Num (a, b)

instance (AddSemigroup a, AddSemigroup b) => AddSemigroup (a, b)

At this point I feel like I must be duplicating instances that are
provided in a standard way in the prelude somewhere, or more likely
I've misunderstood the ideas around creating instances?

Any advice much appreciated,

Stu


More information about the Beginners mailing list