问题描述
这是我一直在努力解决的问题.我需要将两个排序的序列合并为一个排序的序列.理想情况下,该算法应该是延迟求值的,并且不需要从每个序列中缓存一个以上的项目.这不是一个很难解决的难题,而且我已经能够用F#设计许多解决方案.不幸的是,我想出的每个解决方案都存在以下几个问题之一.
Here’s a problem I’ve really been struggling with. I need to merge two sorted sequences into a single sorted sequence. Ideally, the algorithm should be lazy-evaluated, and not require caching more than one item from each sequence. This is not a terribly difficult problem to solve, and I’ve been able to engineer a number of solutions in F#. Unfortunately, every solution I’ve come up with has one of several problems.
-
使用yield!递归调用子序列生成器.这样可以产生美观的解决方案,但是为每个项目创建子序列都是性能杀手.
Recursive calls to subsequence generators using yield!. This produces elegant looking solutions, but the creation of a subsequence for every item is a performance killer.
真正的奥秘和不可维护的代码,带有深度堆叠的匹配开关,多个几乎完全相同的代码块等.
Really arcane and unmaintainable code with deeply-stacked match switches, multiple nearly identical blocks of code, etc.
强制F#进入纯程序模式(大量可变值等)的代码.
Code which forces F# into a purely procedural mode (lots of mutable values, etc.).
我能够在同一滩上找到创始人的所有在线示例.
And all of the online examples I've been able to find founder on the same shoals.
我是否遗漏了一些明显的东西:像是真的很简单,还是显然不可能?有谁知道一个真正优雅的解决方案,该解决方案也有效且功能强大? (它不必纯粹是功能.)否则,我可能最终会缓存子序列并使用列表或数组.
Am I missing something obvious: like it's either really simple or else obviously impossible? Does anyone know of a really elegant solution that is also efficient and mostly functional? (It doesn’t have to be purely functional.) If not, I may end up caching subsequences and using lists or arrays.
推荐答案
在PowerPack中使用LazyList类型.我想我什至可能有这个确切的代码,让我看看...
Use the LazyList type in the PowerPack. I think I maybe even have this exact code lying around, let me look...
编辑
并非完全相同,但请关闭: http://cs.hubfs.net/forums/thread/8136.aspx
not exactly it, but close: http://cs.hubfs.net/forums/thread/8136.aspx
这篇关于如何合并排序的序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!