遍历haskell中的列表 [英] iterating through a list in haskell
问题描述
我有一个字符列表::[[Char]]
.
我需要遍历字符串列表以及每个字符串中的每个字符.
I have a list of list of characters ::[[Char]]
.
I need to iterate both over the list of strings and also over each character in each string.
说,我的列表出现在此变量中.
Say, my list is present in this variable.
let xs
请提出一种简单的迭代方法.
Please suggest an easy way to iterate.
推荐答案
如果要将函数f
应用于列表的每个元素,如下所示:
If you want to apply a function f
to every element of a list like this:
[a, b, c, d] → [f a, f b, f c, f d]
然后map f xs
可以解决问题. map
将元素上的功能转换为列表上的功能.因此,我们可以将其嵌套以处理列表列表:如果f
将a
转换为b
,map (map f)
将[[a]]
转换为[[b]]
.
then map f xs
does the trick. map
turns a function on elements to a function on lists. So, we can nest it to operate on lists of lists: if f
transforms a
s into b
s, map (map f)
transforms [[a]]
s into [[b]]
s.
如果您想对列表的每个元素执行一些IO操作(这更像是传统的迭代),那么您可能正在寻找forM_
: 1
If you instead want to perform some IO action for every element of a list (which is more like traditional iteration), then you're probably looking for forM_
:1
forM_ :: [a] -> (a -> IO b) -> IO ()
您给它提供一个函数,它会按列表中的每个元素依次调用它.例如,forM_ xs putStrLn
是一个IO操作,它将在自己的行上打印出xs
中的每个字符串.这是forM_
的更多使用示例:
You give it a function, and it calls it with each element of the list in order. For instance, forM_ xs putStrLn
is an IO action that will print out every string in xs
on its own line. Here's an example of a more involved use of forM_
:
main = do
...
forM_ xs $ \s -> do
putStrLn "Here's a string:"
forM_ s print
putStrLn "Now it's done."
如果xs
包含["hello", "world"]
,则将打印出来:
If xs
contains ["hello", "world"]
, then this will print out:
Here's a string:
'h'
'e'
'l'
'l'
'o'
Now it's done.
Here's a string:
'w'
'o'
'r'
'l'
'd'
Now it's done.
1 forM_
实际上具有更通用的类型,但我在此显示的更简单的版本在这里更相关.
1 forM_
actually has a more general type, but the simpler version I've shown is more relevant here.
这篇关于遍历haskell中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!