惰性生成 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# 中以 idomatic 的方式做到这一点?
编辑:
这就是我将要使用的(基于 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
}
感谢大家的出色投入。
I want to calculate powerset of a set. Because I don't need the whole powerset at a time, it's better to generate it lazily.
For example:
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"];
}
Since the result is a sequence, I prefer it in the above order. How can I do it in an idomatic way in F#?
EDIT:
This is what I'm going to use (based on BLUEPIXY's answer):
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
}
Thanks everyone for excellent input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
演示
DEMO
来自 F#对于科学家,稍微修改为懒惰
From F# for Scientists, slightly modified to be lazy
这是另一种方法,使用数学而不是递归:
Here's another approach, using maths instead of recursion: