mapM
mapM is a standard function in Haskell's control of monads. It maps a monadic action over a list and sequences the resulting actions, collecting their results in a single monadic value. In other words, it applies a function that returns a monadic result to each element of a list and runs the actions in order, gathering the results.
mapM :: Monad m => (a -> m b) -> [a] -> m [b]
For each element x in the input list, mapM applies the function to produce an action of
Example usage in the IO monad:
mapM putStrLn ["hello","world"]
This prints each string on its own line and returns an IO [()] indicating the unit results for
In the Maybe monad, mapM chains optional computations:
mapM (\x -> if x == 0 then Nothing else Just (x * 2)) [1,2]
returns Just [2,4], while any Nothing in the sequence yields Nothing for the whole result.
Related functions include mapM_, which performs the same sequencing but discards the results, and traverse, which
Overall, mapM is a fundamental tool for combining lists with monadic effects, ensuring effects occur in