# Maximum and Minimum monoids

Roman Cheplyaka roma at ro-che.info
Thu Dec 27 21:25:10 CET 2012

```Wouldn't it be better to have a real algebraic type instead of wrapping
Maybe?

Something like

data Maximum a = MinusInfinity | Maximum a
data Minimum a = PlusInfinity  | Minimum a

Maximum x is more concise than Maximum (Just x), and MinusInfinity is
more descriptive than Maximum Nothing. getMaximum/getMinimum functions
can still return Maybes.

Anyway, I'm +1 to having something along these lines.

Roman

* Gabriel Gonzalez <gabriel439 at gmail.com> [2012-12-27 12:45:42-0600]
> 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