darcs patch: Improve Control.Monad.filterM:

Jon Fairbairn jon.fairbairn at cl.cam.ac.uk
Tue Aug 8 10:40:04 EDT 2006

On 2006-08-08 at 13:37BST Chris Kuklewicz wrote:
> The new one looks better to me.  But the foldr is not needed:
> filterM _ []     =  return []
> filterM p (x:xs) =  do
>     flg <- p x
>     if flg
>        then do ys <- filterM p xs
>                return (x:ys)
>        else filterM p xs

I'm curious to know how this performs:

> filterM p = fmap catMaybes . mapM (predMToMaybe p)

with the subsidiary (and generally useful) predMToMaybe¹
defined something like this:

> predMToMaybe p x
>     =  fmap (\b->if b
>                  then Just x
>                  else Nothing ) $ p x

since this definition of filterM clearly shouldn't hold onto
anything in the second half (. mapM (predMToMaybe p)) and
the first half (fmap catMaybes) will be OK provided that
catMaybes and fmap behave themselves -- and if they don't
they should be given what for.

[1] or perhaps it should be called predFToMaybe since its
    type is
    (Functor f) => (a -> f Bool) -> a -> f (Maybe a)

    (if someone can think of a better name, I'd be glad to
    hear it)

Jón Fairbairn                              Jon.Fairbairn at cl.cam.ac.uk

More information about the Libraries mailing list