我正在尝试通过并集操作将Haskell整数集定义为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)

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

我究竟做错了什么?这似乎很简单,我正在复制在this这样的示例中看到的语法,但是我看不到为什么发生此错误。

最佳答案

自编写此教程以来,(<>)已从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

10-08 18:20