【发布时间】:2020-07-11 09:16:51
【问题描述】:
我正在尝试在 Haskell 中使用幺半群,使用此页面:https://en.wikibooks.org/wiki/Haskell/Monoids。我在终端中输入了以下信息(导入Data.Monoid后):
class Monoid a where
mempty :: a
mappend :: a -> a -> a
mconcat :: [a] -> a
mconcat = foldr mappend memptyhere
newtype Sum a = Sum { getSum :: a }
instance Num a => Monoid (Sum a) where
mempty = Sum 0
Sum x `mappend` Sum y = Sum (x + y)
但是,当我尝试Sum 5 <> Sum 6 <> Sum 10 时,我收到以下消息:
<interactive>:115:1: error:
• Non type-variable argument in the constraint: Semigroup (Sum a)
(Use FlexibleContexts to permit this)
• When checking the inferred type
it :: forall a. (Semigroup (Sum a), Num a) => Sum a
我不明白这些是什么错误,以及为什么 Sum 5 <> Sum 6 <> Sum 10 不起作用。
【问题讨论】:
-
维基书好像有点过时了。后来添加了
Semigroup类型类(hackage.haskell.org/package/base-4.14.0.0/docs/…),Monoid的每个实例也应该是Semigroup的一个实例。 -
你为什么要添加自己的
class Monoid和导入Data.Monoid?注意本书使用mappend,而你使用<>。