Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Int Does Not Implement 'Monoid'?

Tags:

haskell

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?

like image 898
Kevin Meredith Avatar asked Apr 07 '15 18:04

Kevin Meredith


1 Answers

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.

like image 148
Cirdec Avatar answered Nov 01 '22 06:11

Cirdec