Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are mapM and forM interchangeable?

Tags:

haskell

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?

like image 777
demathieu Avatar asked Aug 31 '15 16:08

demathieu


2 Answers

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_.

like image 188
duplode Avatar answered Oct 29 '22 19:10

duplode


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.

like image 41
bheklilr Avatar answered Oct 29 '22 19:10

bheklilr