Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A basic Monoid definition gives "No instance for (Semigroup MyMonoid) arising from the superclasses of an instance declaration"

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.

like image 834
W.P. McNeill Avatar asked Dec 04 '18 22:12

W.P. McNeill


1 Answers

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
like image 122
amalloy Avatar answered Nov 20 '22 10:11

amalloy