简体   繁体   English

有没有办法在Haskell中以编程方式生成一系列列表推导?

[英]Is there a way to generate a series of list comprehensions programmatically in Haskell?

In my ongoing attempt to get better at Haskell, I'm attempting to solve a problem where I'd like to create a series of list comprehensions of this form: 为了不断提高Haskell的水平,我试图解决一个问题,在该问题中,我想创建一系列这种形式的列表理解:

m2 = [[x1,x2] | x1 <- [2..110], x2 <- [x1..111]]
m3 = [[x1,x2,x3] | x1 <- [2..22], x2 <- [x1..22], x3 <- [x2..24]]
m4 = [[x1,x2,x3,x4] | x1 <- [2..10], x2 <- [x1..10], x3 <- [x2..10], x4 <- [x3..12]]
...

Where x1 <= x2 ... <= xn , the number following m is the length of the sublists, and the first n - 1 terms are bounded by the same upper bound, while the nth term is bounded by some larger number. 其中x1 <= x2 ... <= xn ,m之后的数字是子列表的长度,前n-1个词以相同的上限为边界,而第n个词以更大的数为边界。

I could certainly write all of it out by hand, but that's not particularly good practice. 我当然可以手工将所有内容写出来,但这并不是特别好的做法。 I'm wondering if there's a way to generate these lists up to a particular maximum m value. 我想知道是否有一种方法可以生成这些列表,直到达到特定的最大m值。 My immediate thought was Template Haskell, but I don't know enough about it to determine whether it's usable. 我立即想到的是Template Haskell,但我对其了解不足,无法确定它是否可用。 Is there some other solution that's escaping me? 还有其他让我逃脱的解决方案吗?

In pseudo-Haskell, what I'm looking for is some method that does something like: 在伪Haskell中,我正在寻找的是某种执行以下操作的方法:

mOfN n bound term = [ [x1..xn] | x1 <- [2..bound], x2 <- [x1..bound], ..., xn <- [x(n-1)..term] ]

The main issue is that I can't figure out how I would dynamically create x1,x2, etc. 主要问题是我无法弄清楚如何动态创建x1,x2等。

Is this what you are looking for? 这是你想要的?

import Data.List (tails)

mofn 0 xs = [ [] ]
mofn m xs = [ y:zs | (y:ys) <- tails xs, zs <- mofn (m-1) ys ]

ie mofn 3 [1..5] is: mofn 3 [1..5]是:

[[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]]

The key is the tails function which returns successive tails of a list. 关键是tails函数,该函数返回列表的连续尾部。

Update 更新资料

Is this what you are looking for? 这是你想要的?

mofn' 1 lo hi bnd = [ [x] | x <- [lo..bnd] ]
mofn' k lo hi bnd = [ x:ys | x <- [lo..hi], ys <- mofn' (k-1) x hi bnd ]

mofn' 3 1 3 5 is: mofn' 3 1 3 5是:

[[1,1,1], [1,1,2], [1,1,3], [1,1,4], [1,1,5],
 [1,2,2], [1,2,3], [1,2,4], [1,2,5],
 [1,3,3], [1,3,4], [1,3,5],
 [2,2,2], [2,2,3], [2,2,4], [2,2,5],
 [2,3,3], [2,3,4], [2,3,5],
 [3,3,3], [3,3,4], [3,3,5]
]

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

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