如何将 Pair 定义为 Monoid?

W. *_*Zhu 3 haskell monoids

我的数据类型Pair定义为

data Pair a b = Pair a b
Run Code Online (Sandbox Code Playgroud)

我想让它成为幺半群。这是我的定义。

instance (Monoid a,Monoid b) => Monoid (Pair a b) where
    mempty = Pair mempty mempty
    mappend (Pair x1 y1) (Pair x2 y2) = Pair (mappend x1 x2) (mappend y1 y2)
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误。

foldable.hs:3:10: error:
    • Could not deduce (Semigroup (Pair a b))
        arising from the superclasses of an instance declaration
      from the context: (Monoid a, Monoid b)
        bound by the instance declaration at foldable.hs:3:10-49
    • In the instance declaration for ‘Monoid (Pair a b)’
  |
3 | instance (Monoid a,Monoid b) => Monoid (Pair a b) where
  |          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

什么地方出了错?

ama*_*loy 6

mappend不再是 Monoid 的一种方法。你可以实现它,但它应该只是 的同义词(<>),它属于 Monoid 的超类 Semigroup。要实现 Monoid,您还必须实现 Semigroup,并将您的定义放在mappend那里,命名为(<>)