2017-04-05 110 views
-1

我試圖從一組N: 元素中獲取3個元素的所有有序組合,即:["A","B","C","D"]["ABC","ABD","ACD","BCD"]來自set N的haskell的k個元素的組合

我想過寫類似[ x++y++z | pos(x)in list < pos(y) in list < pos(z) in list ]

我會怎麼做呢?

回答

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"] 

但通常你想要一個更可擴展的解決方案(一個在那裏你可以生成元素的組合)。你可以例如定義一個函數combinations :: Int -> [a] -> [[a]],如:

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

,然後你(例如使用一個map)有concat所有元素。

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"])

相關問題