for
但是,可以编写计算(类似于
seq { .. }
IEnumerator<T>
seq
get it here
(代码还包括问题的解决方案)。
然后你可以写下:
// Zip using specified functions for sequences
let zipWithFun f g h (a:seq<_>) (b:seq<_>) =
// Local helper function that works with iterators (xs and ys)
let rec zipWithFunE xs ys = iter {
// Try to get first element from both iterators (mutates the iterators!)
let! x = xs
let! y = ys
match x, y with
| Some(x), Some(y) ->
// If both produced value, then combine values using 'f' & continue
yield f (x, y)
yield! zipWithFunE xs ys
// If only one produced value, yield the value and then return the
// remaining values projected using one of the functions
| Some(rest), _ ->
yield g rest
yield! ys |> Enumerator.map g
| _, Some(rest) ->
yield g rest
yield! ys |> Enumerator.map g
| _ -> () }
// Construct a 'seq' value from a function that processes enumerators
Enumerator.toSeq (fun () ->
zipE (a.GetEnumerator()) (b.GetEnumerator()))
代码的核心部分几乎复制了原始Haskell解决方案的结构,这使得这种方法非常有吸引力,但是您仍然可以直接使用序列,而不必将数据复制到其他数据结构。