
On Tue, Jul 13, 2010 at 04:00:28PM +0100, Tim Cowlishaw wrote:
On 13 Jul 2010, at 15:51, Brent Yorgey wrote:
If it really is an instance of the Monoid type class then you could just write:
maybeMonoid :: (Monoid a) => Maybe a -> Maybe a -> a maybeMonoid x y = fromMaybe mempty $ liftM2 mappend x y
Aha, yes! that's exactly what I was getting at. Presumably I would also then define
Instance Monoid Int where mempty = 0 mappend = (+)
There is already such an instance defined in Data.Monoid, but since (as you note) Int has (at least) two common Monoid instances, the instance is for a newtype wrapper around Int, namely Sum. i.e. it looks like newtype Sum a = Sum { getSum :: a } instance Num a => Monoid (Sum a) where mempty = Sum 0 (Sum x) `mappend` (Sum y) = Sum (x + y) -Brent