Haskell中mapM_和mapM有什么区别? [英] What is the difference between mapM_ and mapM in Haskell?
问题描述
我已经检查了hoogle, http ://hackage.haskell.org/package/base-4.7.0.1/docs/Prelude.html#v:mapM
Hoogle说 mapM _
忽略结果。
但我仍然不知道如何正确使用。
main = mapM_(putStrLn.show)[1,2]
main = mapM(putStrLn.show)[1,2 ]
main = map(putStrLn.show)[1,2]
mapM _
对于仅为其副作用执行某些操作很有用。例如,将字符串打印到标准输出不会返回任何有用的内容 - 它会返回()
。如果我们有三个字符串的列表,我们最终会累积一个 [(),(),()]
列表。构建这个列表在速度和内存使用方面都存在运行时间成本,所以通过使用 mapM _
,我们可以完全跳过这一步。
然而,有时我们需要执行副作用和建立结果列表。如果我们有一个函数,比如
lookupUserById :: UserId - > IO用户
然后我们可以用这个来填充 UserId
s到
用户
s列表:
lookupUsers :: [UserId] - > IO [User]
lookupUsers = mapM lookupUserById
I've already checked hoogle, http://hackage.haskell.org/package/base-4.7.0.1/docs/Prelude.html#v:mapM
Hoogle says mapM_
ignore the results.
But I still don't have idea how to user properly.
main = mapM_ (putStrLn.show) [1,2]
main = mapM (putStrLn.show) [1,2]
main = map (putStrLn.show) [1,2]
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 UserId
s to a list of User
s:
lookupUsers :: [UserId] -> IO [User]
lookupUsers = mapM lookupUserById
这篇关于Haskell中mapM_和mapM有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!