一个更好的方法来映射一个需要IO列表的函数 [英] A better way to map a function that requires IO over a list

查看:76
本文介绍了一个更好的方法来映射一个需要IO列表的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以最近我有一个字符串列表,并且需要独立地遍历每个字符串并执行一些 IO 函数。



所以基本上我得到的是:

  goOverList :: [字符串]  - > IO()
goOverList(x:[])= do
putStrLn x
goOverList(x:xs)= do
goOverList [x]
goOverList xs

main = do
let myList = [first,second,third]
goOverList myList
$ b $ IO 有点复杂,但它的要点是(需要有一个函数超过列表并根据列表成员执行 IO )我希望有人会告诉我如何更好地做到这一点。 goOverList 函数几乎相当于 > mapM_ putStrLn 。 (几乎是因为 mapM _ 也适用于空列表,而你的函数没有)



mapM 是一个函数,它应用 a - >类型的函数。 IO b 1给 a s列表中的每个项目,并返回给您 IO ²列出 b s。 mapM _ mapM 相同,不同之处在于它不会将结果存储在列表中对于返回() putStrLn 那样的动作的感觉。



实际上它比这更一般:函数的类型是 a - > mb 其中 Monad m ,但在这种情况下 m IO



²同样是m。


So lately I have a list of strings, and need to independently go over each one and perform some IO function.

So basically what I have is this:

goOverList :: [String] -> IO ()
goOverList (x:[]) = do
    putStrLn x
goOverList (x:xs) = do
    goOverList [x]
    goOverList xs

main = do
    let myList = ["first", "second", "third"]
    goOverList myList

My IO is a bit more complicated but that is the gist of it (needing to have a function go over a list and do IO based on the list member) I was hoping someone might show me how to do this better.

解决方案

Your goOverList function is almost equivalent to mapM_ putStrLn. (Just almost because mapM_ also works with the empty list while your function does not).

mapM is a function that applies a function of type a -> IO b¹ to each item in a list of as and gives you back an IO² with a list of bs. mapM_ is the same as mapM except that it doesn't store the results in a list (which doesn't make sense for actions that return () like putStrLn does).

¹ Actually it's more general than that: The function has type a -> m b where Monad m, but in this case m is IO.

² Again it's actually m.

这篇关于一个更好的方法来映射一个需要IO列表的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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