From 5bf07866fe34a5b7eb27870ec73a9f44e1c9c37e Mon Sep 17 00:00:00 2001 From: Simon Jakobi Date: Sat, 17 Nov 2018 12:30:12 +0100 Subject: Speed up MonadUtils.mapMaybeM Summary: This version is nearly 2x faster according to a few small benchmarks. Reviewers: bgamari, monoidal Reviewed By: monoidal Subscribers: rwbarton, carter Differential Revision: https://phabricator.haskell.org/D5344 --- compiler/utils/MonadUtils.hs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/compiler/utils/MonadUtils.hs b/compiler/utils/MonadUtils.hs index e86bc49708..8f40f88ba9 100644 --- a/compiler/utils/MonadUtils.hs +++ b/compiler/utils/MonadUtils.hs @@ -30,8 +30,6 @@ module MonadUtils import GhcPrelude -import Maybes - import Control.Applicative import Control.Monad import Control.Monad.Fix @@ -144,9 +142,10 @@ mapSndM f ((a,b):xs) = do { c <- f b; rs <- mapSndM f xs; return ((a,c):rs) } concatMapM :: Monad m => (a -> m [b]) -> [a] -> m [b] concatMapM f xs = liftM concat (mapM f xs) --- | Monadic version of mapMaybe -mapMaybeM :: (Monad m) => (a -> m (Maybe b)) -> [a] -> m [b] -mapMaybeM f = liftM catMaybes . mapM f +-- | Applicative version of mapMaybe +mapMaybeM :: Applicative m => (a -> m (Maybe b)) -> [a] -> m [b] +mapMaybeM f = foldr g (pure []) + where g a = liftA2 (maybe id (:)) (f a) -- | Monadic version of fmap fmapMaybeM :: (Monad m) => (a -> m b) -> Maybe a -> m (Maybe b) -- cgit v1.2.1