我希望计算一个集合的幂集。因为我不需要一次性获取整个幂集,所以最好是惰性生成它。
例如:
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
函数返回一个序列,这在某些情况下可以减少计算量,特别是当不需要枚举整个幂集时。 - kvb