一个更好的方法来映射一个需要IO列表的函数 [英] A better way to map a function that requires IO over a list
问题描述
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 a
s and gives you back an IO
² with a list of b
s. 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屋!