
On 02/20/2015 06:58 PM, Stuart Hungerford wrote:
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.
You only get one instance per type, so the Semigroup/Monoid instances for Integer are "set in stone." When you "import Semigroup" and "import Monoid", those instances come into scope. So in Group.hs, '|.|' and 'identity' are already defined for Integer. All you need is, instance Group Integer where inverse = negate To add different instances, you'll need a newtype wrapper around Integer.