Generalize filterM to Applicative

David Feuer david.feuer at gmail.com
Sun Dec 28 04:59:30 UTC 2014


Currently,

filterM          :: (Monad m) => (a -> m Bool) -> [a] -> m [a]
filterM p        = foldr go (return [])
  where
    go x r = do
      flg <- p x
      ys <- r
      return (if flg then x:ys else ys)


We could change this to


filterM :: (Applicative f) => (a -> f Bool) -> [a] -> f [a]
filterM p = foldr go (pure [])
  where
    go x r = f <$> p x <*> r
       where
          f flg ys = if flg then x:ys else ys


More information about the Libraries mailing list