Re[Haskell-cafe] cursive to foldr

Ben Millwood haskell at
Wed Nov 18 07:43:30 EST 2009

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

which results in the expected behaviour (it's unsatisfyingly
asymmetric, since it should (but can't) produce a Just if the second
argument is Just without pattern-matching on the first, but there is
only so much one can do without involving scary things like unamb).

I'd be interested in what people thought of the relative merits of
this alternative Monoid instance, but perhaps that would be a subject
for a different thread.

More information about the Haskell-Cafe mailing list