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?
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_
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With