Haskell 中的列表理解
我一直在使用以下代码来获取预定数量的数字的所有组合:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相信您想要的是
Control.Monad
中的replicateM
函数。列表 monad 基于“尝试所有可能的组合”,并且普通的
replicate
通过重复某个项目一定次数来创建列表。因此,在给定一些可能值的列表的情况下,replicateM 的结果是从该列表中多次选择项目的所有可能方法的列表。例如:
因此,要将您的函数扩展到任意重复,您可以使用类似以下内容的内容:
...其中您的原始
getList
将相当于getListN 3
。I believe what you want would be the
replicateM
function inControl.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 ofreplicateM
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:
So to extend your function to arbitrary repetitions, you'd use something like:
...where your original
getList
would be equivalent togetListN 3
.万一,任何人都喜欢非 Monadic 解决方案来理解内部工作原理(尽管通过
replicateM
的解决方案很棒!):本质上,通过
foldl
的实现完全可以工作与replacatM 解决方案的方式相同。In case, anyone likes a non-Monadic-solution to understand to inner workings (although, the soliution via
replicateM
is great!):Essentially, this implementation via
foldl
works exactly in the same way as thereplacatM
-solution does.