Re[Haskell-cafe] cursive to foldr
Edward Kmett
ekmett at gmail.com
Wed Nov 18 16:33:17 EST 2009
On Wed, Nov 18, 2009 at 7:43 AM, Ben Millwood <haskell at benmachine.co.uk>wrote:
> It looks quite neat to use the Maybe monoid here:
>
> > import Data.Monoid
> > searchList p = foldr (\x -> if p x then mappend (Just [x]) else id)
> Nothing
>
> but it seems that the Maybe Monoid instance keeps this strict. I
> fiddled with this a bit, and came up with the following:
>
> > instance (Monoid m) => Monoid (Maybe m) where
> > mempty = Nothing -- as usual
> > mappend (Just x) y = Just $ mappend x (fromMaybe mempty y)
> > mappend Nothing y = y
>
The existing Monoid instance for 'Maybe a' lifts what is logically a
Semigroup into a Monoid by extending the domain of the operation with a unit
(Nothing). Alas, This is annoyingly not the same behavior as the MonadPlus
behavior for Maybe, unlike all of the other cases where MonadPlus and Monoid
happen to exist in a manner in which they coincide, and since there is no
Semigroup class, it lies and claims that it transforms Monoid m => Monoid
(Maybe m).
Your version uses mempty from the underlying monoid, so it would break any
code that relied on the existing 'lifted Semigroup' interpretation of the
Maybe Monoid, which safely operate lift Semigroups-that-claim-to-be-Monoids
where mempty = undefined
-Edward Kmett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20091118/6076f691/attachment.html
More information about the Haskell-Cafe
mailing list