mapM package:relude

Map each element of a structure to a monadic action, evaluate these actions from left to right, and collect the results. For a version that ignores the results see mapM_.

Examples

mapM is literally a traverse with a type signature restricted to Monad. Its implementation may be more efficient due to additional power of Monad.
Map each element of a structure to a monadic action, evaluate these actions from left to right, and ignore the results. For a version that doesn't ignore the results see mapM. mapM_ is just like traverse_, but specialised to monadic actions.
The monadic version of the mapMaybe function.
>>> :{
evenInHalf :: Int -> IO (Maybe Int)
evenInHalf n
| even n = pure $ Just $ n `div` 2
| otherwise = pure Nothing
:}
>>> mapMaybeM evenInHalf [1..10]
[1,2,3,4,5]
The mapMaybe function is a version of map which can throw out elements. In particular, the functional argument returns something of type Maybe b. If this is Nothing, no element is added on to the result list. If it is Just b, then b is included in the result list.

Examples

Using mapMaybe f x is a shortcut for catMaybes $ map f x in most cases:
>>> import GHC.Internal.Text.Read ( readMaybe )

>>> let readMaybeInt = readMaybe :: String -> Maybe Int

>>> mapMaybe readMaybeInt ["1", "Foo", "3"]
[1,3]

>>> catMaybes $ map readMaybeInt ["1", "Foo", "3"]
[1,3]
If we map the Just constructor, the entire list should be returned:
>>> mapMaybe Just [1,2,3]
[1,2,3]
Polymorphic version of the concatMapM function.
>>> foldMapM @[Int] (Just . replicate 3) [1..3]
Just [1,1,1,2,2,2,3,3,3]