我想计算一组的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
}
感谢大家的出色表现。
答案 0 :(得分:8)
let rec comb n l =
match n, l with
| 0, _ -> [[]]
| _, [] -> []
| n, x::xs -> List.map (fun l -> x ::l) (comb (n - 1) xs) @ (comb n xs)
let powerset xs = seq {
for i = 0 to List.length xs do
for x in comb i xs -> set x
}
<强>样本强>
> powerset ["a";"b";"c"] |> Seq.iter (printfn "%A");;
set []
set ["a"]
set ["b"]
set ["c"]
set ["a"; "b"]
set ["a"; "c"]
set ["b"; "c"]
set ["a"; "b"; "c"]
val it : unit = ()
答案 1 :(得分:4)
从F# for Scientists,稍加修改为懒惰
let rec powerset s =
seq {
match s with
| [] -> yield []
| h::t -> for x in powerset t do yield! [x; h::x]
}
答案 2 :(得分:0)
这是另一种方法,使用数学而不是递归:
let powerset st =
let lst = Set.toList st
seq [0..(lst.Length |> pown 2)-1]
|> Seq.map (fun i ->
set ([0..lst.Length-1] |> Seq.choose (fun x ->
if i &&& (pown 2 x) = 0 then None else Some lst.[x])))