简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM