Haskell中mapM_和mapM有什么区别? [英] What is the difference between mapM_ and mapM in Haskell?

查看:428
本文介绍了Haskell中mapM_和mapM有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了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 UserIds to a list of Users:

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

这篇关于Haskell中mapM_和mapM有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆