Haskell 中的列表理解

发布于 2024-11-06 20:14:15 字数 389 浏览 1 评论 0原文

我一直在使用以下代码来获取预定数量的数字的所有组合:

getList x = [ [a,b,c] | a <- [1..x], b <- [1..x], c <- [1..x]]

一开始这很好,但我希望扩展该程序以处理非常大的列表,并且我一直认为必须有一个更好的方法来做到这一点。我将如何创建一个函数,它采用与此处相同的参数 x ,以及子列表有多少项的另一个参数。对于四个项目,我会去修改代码:

getList x = [ [a,b,c,d] | a <- [1..x], b <- [1..x], c <- [1..x], d <- [1..x]]

它不需要是列表理解。感谢您的帮助。

I've been using the following code to get all combinations of a pre-determined amount of numbers:

getList x = [ [a,b,c] | a <- [1..x], b <- [1..x], c <- [1..x]]

This was fine to begin with, but I'm looking to expand the program to handle very large lists, and I keep thinking there must be a better way to do this. How would I create a function that takes the same parameter x as here, and also another parameter for how many items the sublists have. For four items I would go and modify the code:

getList x = [ [a,b,c,d] | a <- [1..x], b <- [1..x], c <- [1..x], d <- [1..x]]

It doesn't need to be a list comprehension. Thank you for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

嗫嚅 2024-11-13 20:14:15

我相信您想要的是 Control.Monad 中的 replicateM 函数。

列表 monad 基于“尝试所有可能的组合”,并且普通的 replicate 通过重复某个项目一定次数来创建列表。因此,在给定一些可能值的列表的情况下,replicateM 的结果是从该列表中多次选择项目的所有可能方法的列表。

例如:

> replicateM 2 [0, 1]
[[0,0],[0,1],[1,0],[1,1]]
> replicateM 3 [0, 1]
[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]

因此,要将您的函数扩展到任意重复,您可以使用类似以下内容的内容:

getListN n x = replicateM n [1..x]

...其中您的原始 getList 将相当于 getListN 3

I believe what you want would be the replicateM function in Control.Monad.

The list monad is based on "trying all possible combinations", and plain replicate creates a list by repeating an item some number of times. So the result of replicateM is, given some list of possible values, a list of all possible ways to select an item from that list some number of times.

For example:

> replicateM 2 [0, 1]
[[0,0],[0,1],[1,0],[1,1]]
> replicateM 3 [0, 1]
[[0,0,0],[0,0,1],[0,1,0],[0,1,1],[1,0,0],[1,0,1],[1,1,0],[1,1,1]]

So to extend your function to arbitrary repetitions, you'd use something like:

getListN n x = replicateM n [1..x]

...where your original getList would be equivalent to getListN 3.

呆头 2024-11-13 20:14:15

万一,任何人都喜欢非 Monadic 解决方案来理解内部工作原理(尽管通过 replicateM 的解决方案很棒!):

getListN n = foldl (\ass bs -> [ b:as | b <- bs, as <- ass]) [[]] . replicate n

本质上,通过 foldl 的实现完全可以工作与replacatM 解决方案的方式相同。

In case, anyone likes a non-Monadic-solution to understand to inner workings (although, the soliution via replicateM is great!):

getListN n = foldl (\ass bs -> [ b:as | b <- bs, as <- ass]) [[]] . replicate n

Essentially, this implementation via foldl works exactly in the same way as the replacatM-solution does.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文