16

As I understand forM is the same as mapM, only the arguments are reversed. Does this mean I could replace every forM with a mapM and the other way around, if I reverse the arguments I'm giving them?

2 Answers 2

25

Indeed. forM is literally just...

forM = flip mapM

... so it is the same except for the order of arguments. As a matter of style, forM looks nice when the function argument is a big block of code that you didn't bother giving a name to, as in:

-- Somewhere in a do-block...
results <- forM items $ \item -> do
    -- A do-block using `item`.

Side note: Specially if you are using the latest GHC (and thus the 4.8 version of the base package) I suggest replacing mapM and forM with the equivalent but more general traverse and for functions respectively. The Prelude in base-4.8 exports traverse, while you can find for in Data.Traversable. Similarly, Data.Foldable offers traverse_ and for_, which are strictly more general than mapM_ and forM_.

8

Yes. The definition in base is given as

forM  = flip mapM

With Haskell's equational reasoning this means that you can replace forM with flip mapM, then replace flip with its definition to get a normal looking mapM usage. You can also follow this process backwards to go from mapM to forM.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.