我在Haskell中有一个列表列表。我希望从每个列表中获取一个元素时获得所有可能性。我目前所拥有的是
a = [ [1,2], [10,20,30], [-1,-2] ] -- as an example
whatIWant = [ [p,q,r] | p <- a!!0, q <- a!!1, r <- a!!2 ]
这就是我想要的。但是,这显然不是很好的代码,我正在寻找一种更好的编写列表理解的方法,这样就不会在代码中显示索引号(0,1,2)...这就是我和#39;被卡住了。
我该怎么做?
答案 0 :(得分:2)
使用一个函数(里面使用列表推导),我的解决方案是
combinations :: [[a]] -> [[a]]
combinations [] = []
combinations [l] = map (\ x -> [x]) l
combinations (x:xs) = combine (combinations [x]) (combinations xs)
where combine a b = [ p ++ q | p <- a, q <- b ]
示例:
*Main> combinations [[1, 2, 3], [4, 5, 6]]
[[1,4],[1,5],[1,6],[2,4],[2,5],[2,6],[3,4],[3,5],[3,6]]
*Main> combinations [['a', 'b', 'c'], ['A', 'B', 'C'], ['1', '2']]
["aA1","aA2","aB1","aB2","aC1","aC2","bA1","bA2","bB1",...
"bB2","bC1","bC2","cA1","cA2","cB1","cB2","cC1","cC2"]
编辑:当然,您可以使用sequence
功能,如评论中所示:
*Main> sequence [['a', 'b', 'c'], ['A', 'B', 'C'], ['1', '2']]
["aA1","aA2","aB1","aB2","aC1","aC2","bA1","bA2","bB1",...
"bB2","bC1","bC2","cA1","cA2","cB1","cB2","cC1","cC2"]
答案 1 :(得分:1)
这显然不是一个好的代码
这是关于你可以做到的最好的方法,因为你的约束是输入是一个列表列表。
如果您使用其他类型,例如三个列表,然后您可以在结构上索引。 E.g。
Prelude> let x@(a,b,c) = ( [1,2], [10,20,30], [-1,-2] )
让你写:
Prelude> [ (p,q,r) | p <- a , q <- b , r <- c ]
[(1,10,-1),(1,10,-2),(1,20,-1)
,(1,20,-2),(1,30,-1),(1,30,-2)
,(2,10,-1),(2,10,-2),(2,20,-1)
,(2,20,-2),(2,30,-1),(2,30,-2)]
课程:要避免编制索引,请使用其结构捕获您想要保留的不变量的类型。将数据的维度提升到其类型。