是否有可能实现递归"&的SelectMany QUOT;? [英] Is it possible to implement a recursive "SelectMany"?

查看:211
本文介绍了是否有可能实现递归"&的SelectMany QUOT;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家都知道, 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"]

这篇关于是否有可能实现递归&QUOT;&的SelectMany QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆