我想計算一個集合的powerset。因爲我一次不需要整個權力機構,所以最好懶惰地生成它。懶洋洋地生成powerset
例如:
powerset (set ["a"; "b"; "c"]) =
seq {
set [];
set ["a"];
set ["b"];
set ["c"];
set ["a"; "b"];
set ["a"; "c"];
set ["b"; "c"];
set ["a";"b"; "c"];
}
由於結果是一個序列,我更喜歡它按照上述的順序。我如何在F#中以一種習慣方式來做到這一點?
編輯:
這就是我要使用(基於BLUEPIXY的答案):
let powerset s =
let rec loop n l =
seq {
match n, l with
| 0, _ -> yield []
| _, [] ->()
| n, x::xs -> yield! Seq.map (fun l -> x::l) (loop (n-1) xs)
yield! loop n xs
}
let xs = s |> Set.toList
seq {
for i = 0 to List.length xs do
for x in loop i xs -> set x
}
謝謝大家對出色的輸入。
請注意,您可以使'comb'返回一個序列,如果整個powerset未枚舉,在某些情況下這將需要更少的計算。 – kvb
你說得對。 – BLUEPIXY