[commit: ghc] master: Speed up MonadUtils.mapMaybeM (5bf0786)

git at git.haskell.org git at git.haskell.org
Sat Nov 17 12:53:09 UTC 2018


Repository : ssh://git@git.haskell.org/ghc

On branch  : master
Link       : http://ghc.haskell.org/trac/ghc/changeset/5bf07866fe34a5b7eb27870ec73a9f44e1c9c37e/ghc

>---------------------------------------------------------------

commit 5bf07866fe34a5b7eb27870ec73a9f44e1c9c37e
Author: Simon Jakobi <simon.jakobi at gmail.com>
Date:   Sat Nov 17 12:30:12 2018 +0100

    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


>---------------------------------------------------------------

5bf07866fe34a5b7eb27870ec73a9f44e1c9c37e
 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 e86bc49..8f40f88 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)



More information about the ghc-commits mailing list