给定一个 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
看Maybe , 我懂了:
Monoid a => Monoid (Maybe a)
从 Int未实现
Monoid
type-class,这解释了为什么我不能使用 mappend
与 Maybe Int
.但是,我记得 LYAH我可以使用
Sum
:ghci> let x = Sum 55
ghci> mappend x x
Sum {getSum = 110}
但是,为什么不是
Int
一个幺半群?
最佳答案
Int
不是 Monoid
因为有不止一个明显的Monoid
Int
的实现.
instance Monoid Int where
mempty = 0
mappend = (+)
instance Monoid Int where
mempty = 1
mappend = (*)
newtype
小号 Sum
和 Product
定义于 Data.Monoid
让您轻松选择Monoid
与数字一起使用的实例。
关于haskell - 为什么 Int 不实现 'Monoid' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29499119/