28

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?

    1 Answer 1

    46

    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.

    9
    • 6
      @KevinMeredith If you're using GHC 7.8 or newer then Sum and Product implement Num, so you can do getSum $ mconcat $ take 10 $ iterate (+1) 1, although they don't implement Enum so you can't do getSum $ mconcat [1..10]. In the first expression you can swap getSum for getProduct and it'll still compile.
      – bheklilr
      CommentedApr 7, 2015 at 19:12
    • 9
      Other valid monoid implementations: max and min (with mempty being minBound and maxBound respectively). There are lots of valid implementations.CommentedApr 7, 2015 at 19:19
    • 3
      ... not to mention that it could be minimum, maximum, first positive number, and so on.
      – AJF
      CommentedApr 7, 2015 at 19:45
    • 5
      Since Int is fixed size, we also have various bitwise operations.CommentedApr 7, 2015 at 21:04
    • 2
      I think it's an interesting and not always obvious question of what rules to follow when a type allows multiple lawful instances of the same class . In some cases, like Int and Monoid here, the choice has been not to implement the class at all, and leave the instances to newtypes, because there's no obvious choice of one as the default. In the case of the Applicative [] instance, on the other hand, only one of them is compatible with the Monad instance, which determines the choice. Then there are cases like Monoid Maybe instance which many people dislike...CommentedApr 7, 2015 at 22:51

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.