问题描述
所以最近我有一个字符串列表,并且需要独立地遍历每个字符串并执行一些 > mapM_ putStrLn 。 (几乎是因为 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列表的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!