计算 n 元笛卡尔积
给定两个列表,我可以生成所有排列的列表这两个列表的笛卡尔积:
permute :: [a] -> [a] -> [[a]]
permute xs ys = [ [x, y] | x <- xs, y <- ys ]
Example> permute [1,2] [3,4] == [ [1,3], [1,4], [2,3], [2,4] ]
如何扩展排列,以便不需要两个列表,而是需要一个列表(长度为n)的列表并返回一个列表列表(长度为n)
permute :: [[a]] -> [[a]]
Example> permute [ [1,2], [3,4], [5,6] ]
== [ [1,3,5], [1,3,6], [1,4,5], [1,4,6] ] --etc
我在Hoogle上找不到任何相关内容。唯一与签名匹配的函数是transpose
,它不会产生所需的输出。
Given two lists, I can produce a list of all permutations the Cartesian Product of these two lists:
permute :: [a] -> [a] -> [[a]]
permute xs ys = [ [x, y] | x <- xs, y <- ys ]
Example> permute [1,2] [3,4] == [ [1,3], [1,4], [2,3], [2,4] ]
How do I extend permute so that instead of taking two lists, it takes a list (length n) of lists and returns a list of lists (length n)
permute :: [[a]] -> [[a]]
Example> permute [ [1,2], [3,4], [5,6] ]
== [ [1,3,5], [1,3,6], [1,4,5], [1,4,6] ] --etc
I couldn't find anything relevant on Hoogle.. the only function matching the signature was transpose
, which doesn't produce the desired output.
Edit: I think the 2-list version of this is essentially the Cartesian Product, but I can't wrap my head around implementing the n-ary Cartesian Product. Any pointers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我找到了 Eric Lippert 的文章 使用 LINQ 计算笛卡尔积 对于提高我对正在发生的事情的理解非常有帮助。这里有一个或多或少的直接翻译:
或者使用更多“Haskell-y”简洁、无意义的参数名称;)
这最终与发布的 sclv 非常相似。
I found Eric Lippert's article on computing Cartesian product with LINQ quite helpful in improving my understanding of what was going on. Here's a more-or-less direct translation:
Or with more "Haskell-y" terse, meaningless parameter names ;)
This winds up being quite similar to sclv posted after all.
这是我简单地实现它的方法,仅使用列表理解。
Here is my way of implementing it simply, using only list comprehensions.
作为 jleedev 答案的补充(无法在评论中格式化):
单子函数的快速未经检查的替换:
......
列表函数对
As a supplement to jleedev's answer (couldn't format this in the comments):
A quick unchecked substitution of list functions for monadic ones:
....
....
如果你想对输出有更多的控制,你可以使用列表作为应用函子,例如:
假设你想要一个元组列表:
而且它看起来也很酷......
If you want to have more control over the output, you can use a list as applicative functor, e.g.:
Let's say you want a list of tuples instead:
And it looks kind of cool, too...
您可以通过两种方式执行此操作:
You can do this in 2 ways: