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

查看:33
本文介绍了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.

推荐答案

这对于列表推导式来说非常容易.要获得列表xsys 的笛卡尔积,我们只需要为每个元素 取元组(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屋!

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