Haskell 中 2 个列表的笛卡尔积 [英] Cartesian product of 2 lists in Haskell
问题描述
我希望在 Haskell 中生成 2 个列表的笛卡尔积,但我不知道如何去做.笛卡尔积给出了列表元素的所有组合:
I wish to produce the Cartesian product of 2 lists in Haskell, but I cannot work out how to do it. The cartesian product gives all combinations of the list elements:
xs = [1,2,3]
ys = [4,5,6]
cartProd :: [a] -> [b] -> [(a,b)]
cartProd xs ys ==> [(1,4),(1,5),(1,6),(2,4),(2,5),(2,6),(3,4),(3,5),(3,6)]
这不是一个实际的家庭作业问题,也与任何此类问题无关,但解决此问题的方式可能对我遇到的问题有所帮助.
This is not an actual homework question and is not related to any such question, but the way in which this problem is solved may help with one I am stuck on.
推荐答案
这对于列表推导式来说非常容易.要获得列表xs
和ys
的笛卡尔积,我们只需要为每个元素 取元组
和 (x,y)
xs
中的 >xys
中的每个元素 y
.
This is very easy with list comprehensions. To get the cartesian product of the lists xs
and ys
, we just need to take the tuple (x,y)
for each element x
in xs
and each element y
in ys
.
这给了我们以下列表理解:
This gives us the following list comprehension:
cartProd xs ys = [(x,y) | x <- xs, y <- ys]
这篇关于Haskell 中 2 个列表的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!