haskell - 为什么 Int 不实现 'Monoid' ?

标签 haskell

给定一个 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,这解释了为什么我不能使用 mappendMaybe 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/

相关文章:

haskell - 检测什么函数引发了异常 Prelude。!! : negative index

haskell - Haskell中的同构 `fmap`

haskell - 如何在 State monad 中包装链式有状态计算?

haskell - 如何在 Nix 中使用特定版本的 Haskell 包?

haskell - 仆人处理程序中的任一计算

algorithm - 在 Haskell 中表示计算图

haskell - 在 Haskell 中解析大型日志文件

json - 我对 Haskell 的 Text.JSON 的使用被认为是丑陋的?

performance - 为什么 ByteString 不是 Vector Word8?

haskell - 在 haskell 中构建图形结构