A basic Monoid definition gives “No instance for (Semigroup MyMonoid) arising from the superclasses

瘋狂的貓貓啊發表於2021-01-04

在定義一個自己的Monoid時haskell報了錯誤:

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)

報錯:

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

解決方法:

(<>)已從Monoid移到Semigroup,並且所有Monoid例項也必須也是Semigroup。mappend只是的同義詞(<>)。因此,需要兩個例項:

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

instance Monoid MyMonoid where
  mempty = MyMonoid S.empty

 

相關文章