Maximum and Minimum monoids

Gabriel Gonzalez gabriel439 at gmail.com
Thu Dec 27 19:45:42 CET 2012


I don't know if this has been brought up before or not, but would it be 
possible to add the Maximum and Minimum monoids to Data.Monoid?  The 
following implementations extend the traditional semigroups using Maybe.

******

newtype Maximum a = Maximum { getMaximum :: Maybe a }

instance (Ord a) => Monoid (Maximum a) where
     mempty = Maximum Nothing

     mappend (Maximum Nothing) m2 = m2
     mappend m1 (Maximum Nothing) = m1
     mappend (Maximum (Just a1)) (Maximum (Just a2)) = Maximum (Just 
(max a1 a2))

newtype Minimum a = Minimum { getMinimum :: Maybe a }

instance (Ord a) => Monoid (Minimum a) where
     mempty = Minimum Nothing

     mappend (Minimum Nothing) m2 = m2
     mappend m1 (Minimum Nothing) = m1
     mappend (Minimum (Just a1)) (Minimum (Just a2)) = Minimum (Just 
(min a1 a2))

******

These also give the correct behavior when folding empty structures by 
returning Nothing.

The reason I'm asking is that my `pipes` library uses `WriterT` to 
implement folds and having the above monoids lets me implement minimum 
and maximum folds elegantly.  I can always provide these monoids myself, 
but I feel like they belong in Data.Monoid.



More information about the Libraries mailing list