What is the difference between mapM_ and mapM in Haskell?

后端 未结 4 378
野的像风
野的像风 2021-02-01 16:25

I\'ve already checked Hoogle, http://hackage.haskell.org/package/base-4.7.0.1/docs/Prelude.html#v:mapM, which says that mapM_ ignores the results.

However,

4条回答
  •  醉酒成梦
    2021-02-01 17:27

    mapM_ is useful for executing something only for its side effects. For example, printing a string to standard output doesn't return anything useful - it returns (). If we have a list of three strings, we would end up accumulating a list[(), (), ()]. Building this list has a runtime cost, both in terms of speed and memory usage, so by using mapM_ we can skip this step entirely.

    However, sometimes we need to execute side effects and build up a list of the results. If we have a function such as

    lookupUserById :: UserId -> IO User
    

    Then we can use this to inflate a list of UserIds to a list of Users:

    lookupUsers :: [UserId] -> IO [User]
    lookupUsers = mapM lookupUserById
    

提交回复
热议问题