21
votes

I am attempting to define Haskell integer sets with the union operation as a Monoid.

module MyMonoid where

import qualified Data.IntSet as S

data MyMonoid = MyMonoid S.IntSet

instance Monoid MyMonoid where
  mempty = MyMonoid S.empty
  MyMonoid m1 `mappend` MyMonoid m2 = MyMonoid (S.union m1 m2)

I get the error

 No instance for (Semigroup Markup)
    arising from the superclasses of an instance declaration
 In the instance declaration for ‘Monoid MyMonoid’

What am I doing wrong? This seems so simple, and I'm copying the syntax I see in examples like this, but I can't see why this error is occurring.

1

1 Answers

30
votes

Since that tour was written, (<>) has been moved from Monoid to Semigroup, and all Monoid instances are required to also be Semigroup. mappend is just a synonym for (<>). So, you need two instances:

instance Semigroup MyMonoid where
  MyMonoid m1 <> MyMonoid m2 = MyMonoid (S.union m1 m2)

instance Monoid MyMonoid where
  mempty = MyMonoid S.empty