Haskell中的2个列表的笛卡尔积 [英] Cartesian product of 2 lists in Haskell

查看:172
本文介绍了Haskell中的2个列表的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在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 中的每个元素 x 以及每个元素<$在code> ys 中有c $ c> 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆