【发布时间】:2012-01-10 00:07:26
【问题描述】:
这是我在这个问题上的失败尝试,如果有任何帮助,我们将不胜感激。
我试图为在急切列表上工作的电源组提出最佳算法。这部分似乎工作正常。我遇到问题的部分是将其翻译为与序列一起使用,以便它可以在流式\无限列表上运行它。我真的不喜欢 yield 语法可能是因为我不太了解它,但我宁愿拥有它而不使用 yield 语法。
//All Combinations of items in a list
//i.e. the Powerset given each item is unique
//Note: lists are eager so can't be used for infinite
let listCombinations xs =
List.fold (fun acc x ->
List.collect (fun ys -> ys::[x::ys]) acc) [[]] xs
//This works fine (Still interested if it could be faster)
listCombinations [1;2;3;4;5] |> Seq.iter (fun x -> printfn "%A" x)
//All Combinations of items in a sequence
//i.e. the Powerset given each item is unique
//Note: Not working
let seqCombinations xs =
Seq.fold (fun acc x ->
Seq.collect (fun ys ->
seq { yield ys
yield seq { yield x
yield! ys} }) acc) Seq.empty xs
//All Combinations of items in a sequence
//i.e. the Powerset given each item is unique
//Note: Not working (even wrong type signature)
let seqCombinations2 xs =
Seq.fold (fun acc x ->
Seq.collect (fun ys ->
Seq.append ys (Seq.append x ys)) acc) Seq.empty xs
//Sequences to test on
let infiniteSequence = Seq.initInfinite (fun i -> i + 1)
let finiteSequence = Seq.take 5 infiniteSequence
//This should work easy since its in a finite sequence
//But it does not, so their must be a bug in 'seqCombinations' above
for xs in seqCombinations finiteSequence do
for y in xs do
printfn "%A" y
//This one is much more difficult to get to work
//since its the powerset on the infinate sequence
//None the less If someone could help me find a way to make this work
//This is my ultimate goal
let firstFew = Seq.take 20 (seqCombinations infiniteSequence)
for xs in firstFew do
for y in xs do
printfn "%A" y
【问题讨论】:
-
在一组大小为 N 的 powerset 中有 2^N 个元素,因此即使对于一组只有 60 个元素的集合,您看到的 powerset 大小约为 10^18 个元素,您'永远无法完全列举。通过使用序列而不是列表,您可能会使用更少的内存,但如果您能更好地解释您的目标,将会很有帮助。
-
我的目标是看看我可以在 f# 中将惰性 eval 序列推到多远,这似乎是一个简单但又足够复杂的问题。我想以绝对最懒惰的方式制作无限集的幂集,同时在代码中保持一些优雅和良好的性能。
-
这很好,但考虑到即使是中等大小的集合的 powerset 中的元素数量也非常多,如果你想用结果,但您尚未指定订单。
-
您建议以什么顺序返回值。它们可以以可索引的方式返回吗?实际上可以仅根据输入计算索引吗?谢谢。
-
我想不出一个具体的例子,但也许你正在寻找一个服从某些属性的最小集合(你知道存在一个)。当然,对于无限集的幂集,您不能按严格递增的顺序进行(或者您只会在枚举单元素子集的面颊解决方案中重现 Daniel 的舌头),但您可能会找到一些顺序你知道会命中你关心的实例。
标签: visual-studio math f# functional-programming