Maximum and Minimum monoids

Sjoerd Visscher sjoerd at w3future.com
Thu Dec 27 22:14:48 CET 2012


Can't you use Option (Max a) from the semigroups package?

Sjoerd

On Dec 27, 2012, at 7:45 PM, Gabriel Gonzalez <gabriel439 at gmail.com> wrote:

> 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.
> 
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://www.haskell.org/mailman/listinfo/libraries




More information about the Libraries mailing list