我想计算一组的幂集。因为我一次不需要整个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
}
感谢大家的出色投入。