是否可以实现递归“SelectMany"? [英] Is it possible to implement a recursive "SelectMany"?

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

问题描述

众所周知,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 的实现,即热切地评估,但我仍然在摸索如何制作一个懒惰的评估,比如,使用yield 关键字.

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# 中是微不足道的.

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"]

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

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