鉴于Maybe Int,我试着mappend自己.
$let x = Just 55 :: Maybe Int
$mappend x x
<interactive>:126:1:
No instance for (Monoid Int) arising from a use of `mappend'
In the expression: mappend x x
In an equation for `it': it = mappend x x
Run Code Online (Sandbox Code Playgroud)
看着Maybe,我看到:
Monoid a => Monoid(也许是a)
由于Int没有实现Monoid类型类,这就解释了为什么我不能使用mappend它Maybe Int.
但是,我记得LYAH我可以使用Sum:
ghci> let x = Sum 55
ghci> mappend x x
Sum {getSum = 110}
Run Code Online (Sandbox Code Playgroud)
但是,为什么不是IntMonoid?
Cir*_*dec 41
Int不是Monoid因为有不止一个明显的Monoid实现Int.
instance Monoid Int where
mempty = 0
mappend = (+)
instance Monoid Int where
mempty = 1
mappend = (*)
Run Code Online (Sandbox Code Playgroud)
该newtype小号Sum和Product定义在Data.Monoid让你轻松选择哪些Monoid情况下用数字来使用.