haskell - 将列表拆分为可能的元组列表

标签 haskell tuples list-comprehension

我需要将列表拆分为所有可能的元组列表,但我不确定如何执行此操作。

例如:

pairs ["cat","dog","mouse"]

应该导致:
[("cat","dog"), ("cat","mouse"), ("dog","cat"), ("dog","mouse"), ("mouse","cat"), ("mouse","dog")]
我能够形成前两个,但我不确定如何获得其余的。

这是我到目前为止所拥有的:
pairs :: [a] -> [(a,a)]
pairs (x:xs) = [(m,n) | m <- [x], n <- xs]

最佳答案

您可以使用列表理解:

allpairs :: Eq a => [a] -> [(a,a)]
allpairs xs = [ (x1,x2) | x1 <- xs, x2 <- xs, x1 /= x2 ]

关于haskell - 将列表拆分为可能的元组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12869097/

相关文章:

haskell - Haskell中Either和Except在用法上有什么区别?

haskell - Haskell 中的仿函数设计模式

c++ - 为什么我不能执行 tupleVar.get(3) 或 .get<3>()?

python - 通过与第二个列表比较从列表中删除项目,Python

python - 创建没有特定范围的数组

haskell - 尝试实现 (>>=) 函数以创建自定义 monad 转换器时键入错误

tuples - common-lisp 中有 'tuple' 等价物吗?

Python 类型错误 : can only concatenate tuple (not "str") to tuple

python - 获取列表部分的相应总和

exception - 是否可以通过向 Haskell 添加一个新功能(我称之为 "subtype system")来发现用 Haskell 编写的程序中的大部分错误?