Given a Maybe Int, I tried to mappend it to itself.
$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
Looking at Maybe, I see:
Monoid a => Monoid (Maybe a)
Since Int does not implement Monoid type-class, that explains why I can't use mappend with Maybe Int.
But, I remembered from LYAH that I can use Sum:
ghci> let x = Sum 55
ghci> mappend x x
Sum {getSum = 110}
But, why isn't Int a Monoid?
Int isn't a Monoid because there's more than one obvious Monoid implementation for Int.
instance Monoid Int where
    mempty  = 0
    mappend = (+)
instance Monoid Int where
    mempty  = 1
    mappend = (*)
The newtypes Sum and Product defined in Data.Monoid allow you to easily select which Monoid instance to use with numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With