Proposal: Max and Min for Monoid
Gregory Collins
greg at gregorycollins.net
Thu Sep 23 13:47:48 EDT 2010
Felipe Lessa <felipe.lessa at gmail.com> writes:
> On Thu, Sep 23, 2010 at 12:58 PM, Jake McArthur <jake.mcarthur at gmail.com> wrote:
>
>>> -- | Ordered monoid under 'max'.
>>> newtype Max a = Max { getMax :: a }
>>> deriving (Eq, Ord, Read, Show, Bounded)
>>>
>>> instance (Ord a, Bounded a) => Monoid (Max a) where
>>> mempty = Max minBound
>>> Max a `mappend` Max b = Max (a `max` b)
>
> Why should we prefer this monoid over
>
>> data Max a = Minimum | Max a
>> deriving (Eq, Ord, Read, Show)
>>
>> instance Ord a => Monoid (Max a) where
>> mempty = Minimum
>> Minimum `mappend` x = x
>> x `mappend` Minimum = x
>> Max a `mappend` Max b = Max (a `max` b)
You're right, the original wouldn't fly because there are unbounded
types (like Integer) that you'd like to be able to use with Max/Min.
Rather than your proposal I would suggest that Max/Min mirror
the existing First/Last, namely:
newtype Max a = Max { getMax :: Maybe a }
deriving (Eq, Ord, Read, Show)
instance (Ord a) => Monoid (Max a) where
mempty = Max Nothing
mappend = max
G
--
Gregory Collins <greg at gregorycollins.net>
More information about the Libraries
mailing list