列表组合(n选择k)返回元组(选择,未选择)而不仅仅(选择)

时间:2014-01-06 17:29:15

标签: f#

我想改变以下函数(或创建一个全新的函数),以便它返回(选择,未选择)而不仅仅是(选择):

let rec comb n l = 
    match n, l with
    | 0, _ -> [[]]
    | _, [] -> []
    | k, (x::xs) -> List.map ((@) [x]) (comb (k-1) xs) @ comb k xs

目前,

comb 2 ["R";"G";"B"]

返回

[["R"; "G"]; ["R"; "B"]; ["G"; "B"]]

我希望它返回

[(["R"; "G"], ["B"]); (["R"; "B"], ["G"]); (["G"; "B"], ["R"])]

我的大多数问题是我对当前函数的最后一行发生的事情缺乏了解。

1 个答案:

答案 0 :(得分:2)

应该是这样的:

let rec comb n l = 
    match n, l with
    | 0, l -> [[],l]
    | _, [] -> []
    | k, (x::xs) -> 
        [for (yes,no) in comb (k-1) xs do
            yield x::yes,no
         for (yes,no) in comb k xs do
            yield yes,x::no]