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.
-
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.
-
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.
Use the LazyList type in the PowerPack. I think I maybe even have this exact code lying around, let me look…
EDIT
not exactly it, but close: http://cs.hubfs.net/forums/thread/8136.aspx