[Haskell-beginners] Fwd: My first functioning haskell project - a steganography utility

Brent Yorgey byorgey at seas.upenn.edu
Tue Jul 13 11:34:26 EDT 2010


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


More information about the Beginners mailing list