No Monoid instance for Integer

I am in my Haskell journey and came across Chapter 15.6 - Why Integer doesn’t have a Monoid from the purple book Haskell Programming From Frist Principles.

Is this limited to Integer type? It feels to me that it should be generalized to Int, Float, Double, etc… all number types.

Because the only reason for Integer to not have a Monoidal instance is because its uniqueness is not specified, ie. Sum or Product wrappers have to be applied.

Indeed, most type which implements Num does not implement Monoid.

2 Likes

You can check this in GHCi if you’re ever unsure about something. For example

x = 1 :: Float
mappend x x

gives

2:1: error:

  • No instance for (Monoid Float) arising from a use of `mappend’
  • In the expression: mappend x x
    In an equation for `it’: it = mappend x x

confirming what you suspected.

2 Likes

Haskell class instances need to (usually) obey coherence, meaning that there exists at most one canonical instance for a type. This is important so that all operations behave in expected ways, and it’s just not reasonable to assume the additive monoid is the obvious instance for all Num types.

1 Like