Data.Monoid

Ross Paterson ross at soi.city.ac.uk
Tue Jul 5 07:23:15 EDT 2005


We can only have one instance of a class for a particular type, so how
do we choose?

The module Data.Monoid contains the instance

	instance Monoid (a -> a) where
		mempty  = id
		mappend = (.)

I want to argue that a more natural instance is the pointwise lifting:

	instance Monoid b => Monoid (a -> b) where
		mempty _ = mempty
		mappend f g x = f x `mappend` g x

This instance is compositional, in that it builds instances for complex
types (like functions of many arguments) out of instances for simpler
ones, and it's consistent with the instances for tuples.  It's also
Haskell 98.

If the second instance were used instead, the first could be replaced
with one for

	data Endo a = Endo { runEndo :: a -> a }

That's a bit awkward, but not as much as simulating the pointwise
lifting by hand.


More information about the Libraries mailing list