简体   繁体   English

Haskell中的双列表理解

[英]Double List Comprehension in Haskell

I'm trying to implement an array as a list of lists in Haskell. 我正在尝试将数组实现为Haskell中的列表列表。 In particular, I have some array m that I'm given, and a predicate p that I want to be satisfied, and I want to create a list of indices (x,y) such that the x th element of the y th list satisfies p . 特别是,我有一些我给出的数组m ,以及一个我想要满足的谓词p ,我想创建一个索引列表(x,y) ,使得第y个列表中的第x个元素满足p I set this up as the following list comprehension: 我把它设置为以下列表理解:

[(x,y) | x<-[1..],y<-[1..],p ((m !! y) !! x)]  

Which throws up an error when it tries to find an element of m in the first row that doesn't exist. 当它试图在第一行中找到不存在的m元素时会引发错误。 I can see one immediate way to fix this is to just change the inner comprehensions on x and y to something like y<-[1..length m] but I feel like there's a cuter way that exploits laziness. 我可以看到一个立即解决这个问题的方法就是将xy的内部理解改为y<-[1..length m]但我觉得有一种可行的方法可以利用懒惰。 I just don't know what it is. 我只是不知道它是什么。

Indeed there is. 的确有。 The common idiom for getting list elements together with their indices is to use zip : 获取列表元素及其索引的常用习惯是使用zip

[(x,y) | (x,mx) <- zip [1..] m, (y,mxy) <- zip [1..] mx, p mxy]

Also: 也:

  • !! is quite inefficient, especially when extracting many elements from a list, so it's best to try to avoid it when possible. 是非常低效的,特别是从列表中提取许多元素时,所以最好尽可能避免使用它。
  • List indices usually start with 0 in Haskell. 列表索引通常在Haskell中以0开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM