来自集合N haskell的k个元素的组合

时间:2017-04-05 11:15:13

标签: list haskell combinations

我想从一组N中获取3个元素的所有有序组合: 元素,即:["A","B","C","D"] - > ["ABC","ABD","ACD","BCD"]

我想过写一些像[ x++y++z | pos(x)in list < pos(y) in list < pos(z) in list ]

这样的东西

我该怎么做?

2 个答案:

答案 0 :(得分:3)

您可以为三个元素编写函数,例如使用tails :: [a] -> [[a]]

[x++y++z | (x:xs) <- tails list, (y:ys) <- tails xs, (z:_) <- tails ys]

这会产生:

Prelude> :m Data.List
Prelude Data.List> (\list -> [x++y++z | (x:xs) <- tails list, (y:ys) <- tails xs, (z:_) <- tails ys]) ["A","B","C","D"]
["ABC","ABD","ACD","BCD"]

但通常您需要更强大的可扩展解决方案(您可以在其中生成 k 元素的组合)。例如,您可以定义一个函数combinations :: Int -> [a] -> [[a]],如:

combinations 0 _ = [[]]
combinations n ls = [ (x:ys) | (x:xs) <- tails ls, ys <- combinations (n-1) xs ]

然后你必须concat所有元素(例如使用map)。

答案 1 :(得分:0)

你去了:

combinations 0 lst = [[]]
combinations k lst = do
    (x:xs) <- tails lst
    rest   <- combinations (n-1) xs
    return $ x : rest

现在,要获得所需的结果,请使用map concat (combinations 3 ["A","B","C","D"])