[Haskell-beginners] How to manage typeclass hierarchies and instances?

Stuart Hungerford stuart.hungerford at gmail.com
Fri Feb 20 23:58:36 UTC 2015


Hi,

I'm experimenting with Haskell typeclasses and could do with some
advice on managing superclasses and instance declarations. Suppose I
have these modules (please ignore any misunderstandings of abstract
algebra concepts):

-- in Semigroup.hs

class Semigroup a where
  (|.|) :: a -> a -> a

instance Semigroup Integer where
  (|.|) = (+)


-- In Monoid.hs

class (Semigroup a) => Monoid a where
  identity :: a

instance Monoid Integer where
  identity = 0


-- In Group.hs

class (Monoid a) => Group a where
  inverse :: a -> a

instance Group Integer where
  (|.|)    = (+)
  identity = 0
  inverse  = (-)


In Group.hs I'm trying to create an (additive) group instance for
Integer values but GHC complains that (|.|) and identity are not
"visible" typeclass methods.

I understand that if I explicitly recreate Semigroup and Monoid
instances for Integer in Group.hs it will fix the visibility issue--at
the cost of duplicating the instances already defined in Semigroup.hs
and Monoid.hs.

I'm starting to wonder whether it's a good idea to create typeclass
instances in the same modules as the typeclass definitions? In my case
I could create a separate Instances.hs with the instance declarations
but how do Haskellers generally handle this situation?

Thanks,

Stu


More information about the Beginners mailing list