[英]How do I print out each item in a list of lists in Haskell?
I have a list like: 我有一个列表,如:
[[1,2,3,4,5],[6,7,8,9]]
I'm trying to do it using list comprehension and have got as far as: 我正在尝试使用列表理解来做到这一点,并已达到:
each_in_lists x = [show y | y <- x]
where x
is the list of lists. 其中
x
是列表列表。
Are you trying to convert it to string 您是否尝试将其转换为字符串
> let x = [[1,2,3,4,5],[6,7,8,9]]
> [show a | y <- x, a <- y]
["1","2","3","4","5","6","7","8","9"]
If you are trying to print, use print
. 如果您要打印,请使用
print
。 print
uses the show instance of the elements to convert it to string and then uses putStrLn
. print
使用元素的show实例将其转换为字符串,然后使用putStrLn
。
> mapM_ (mapM_ print) x
1
2
3
4
5
6
7
8
9
Extending Satvik mapM_ answer some I think it makes the code more composable if instead of using a nested structure like: 扩展Satvik mapM_回答一些我认为如果不使用嵌套结构,它会使代码更具组合性:
> mapM_ (mapM_ print) x
a structure that takes advantage of function composition. 一种利用功能组合的结构。
> (mapM_.mapM_) print x
The advantage of this is that you can then simply extend this to list of list of list, [[[a]]] by just adding another mapM_ . 这样做的好处是你可以通过添加另一个mapM_简单地将它扩展到列表列表,[[[a]]]。
> (mapM_.mapM_.mapM_) print x
This composition concept can be taken even further to include tuples [[(a,a)]] and data structures. 可以进一步采用这种组合概念来包括元组[[(a,a)]]和数据结构。 This is done in lens .
这是在镜头中完成的。 An example print all the elements of [(a,a)] would be:
打印[(a,a)]所有元素的示例如下:
mapMOf_ (traverse.both) print [(1,2),(3,4),(5,6)]
The other answers so far share what I think is a big flaw: it's always good to split a problem into smaller subproblems, and they don't do it. 到目前为止,其他答案分享了我认为是一个很大的缺陷:将问题分解为较小的子问题总是好的,而且他们不这样做。 In this case, the applicable subproblems are:
在这种情况下,适用的子问题是:
The standard function that does #1 is concat
: #1的标准函数是
concat
:
>>> concat [[1,2,3,4,5],[6,7,8,9]]
[1,2,3,4,5,6,7,8,9]
Now, the easiest way to print the elements is mapM_ print
, as other answers have suggested: 现在,打印元素的最简单方法是
mapM_ print
,正如其他答案所示:
>>> mapM_ print (concat [[1,2,3,4,5],[6,7,8,9]])
1
2
3
4
5
6
7
8
9
This generalizes to all sorts of cases, BTW: in Haskell, the straightforward way of sequentially iterating over the elements of some structure is to convert it to a flat list, and then process the list. 这概括为各种情况,BTW:在Haskell中,顺序迭代某些结构元素的简单方法是将其转换为平面列表,然后处理列表。
Assuming you're trying to flatten the list and want to use list comprehension as much as possible, I think the following is as close as you'll get. 假设您正在尝试压缩列表并希望尽可能多地使用列表理解,我认为以下内容尽可能接近。
x = [[1,2,3,4,5],[6,7,8,9]]
sequence [print z | y <- x, z <- y]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.