是否有可能实现递归"&的SelectMany QUOT;?递归、有可能、SelectMany、QUOT

2023-09-03 03:19:59 作者:女生情敌是LOL@

大家都知道, Enumerable.SelectMany 变平序列序列成一个序列。如果我们想要,可以拼合序列的序列的序列和方法等递归?

As we all know, Enumerable.SelectMany flattens a sequence of sequences into a single sequence. What if we wanted a method that could flatten sequences of sequences of sequences, and so on recursively?

我很快想出了一个实现使用的ICollection< T> ,即急切地评价,但我仍然抓我的头,如何使一个延迟加载评估的,比方说,使用收益率关键字。

I came up quickly with an implementation using an ICollection<T>, i.e. eagerly evaluated, but I'm still scratching my head as to how to make a lazily-evaluated one, say, using the yield keyword.

static List<T> Flatten<T>(IEnumerable list)  {
    var rv = new List<T>();
    InnerFlatten(list, rv);
    return rv;
}

static void InnerFlatten<T>(IEnumerable list, ICollection<T> acc) {
    foreach (var elem in list) {
        var collection = elem as IEnumerable;
        if (collection != null) {
            InnerFlatten(collection, acc);
        }
        else {
            acc.Add((T)elem);
        }
    }
}

任何想法?在任何.NET语言欢迎的例子。

Any ideas? Examples in any .NET language welcome.

推荐答案

这是微不足道的F#与递推数列前pressions。

This is trivial in F# with recursive sequence expressions.

let rec flatten (items: IEnumerable) =
  seq {
    for x in items do
      match x with
      | :? 'T as v -> yield v
      | :? IEnumerable as e -> yield! flatten e
      | _ -> failwithf "Expected IEnumerable or %A" typeof<'T>
  }

测试:

// forces 'T list to obj list
let (!) (l: obj list) = l
let y = ![["1";"2"];"3";[!["4";["5"];["6"]];["7"]];"8"]
let z : string list = flatten y |> Seq.toList
// val z : string list = ["1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"]