用C#编写F#递归文件夹访问者-seq vs IEnumerable [英] Writing the F# recursive folder visitor in C# - seq vs IEnumerable

查看:60
本文介绍了用C#编写F#递归文件夹访问者-seq vs IEnumerable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在F#中使用此递归访问者"

I often use this recursive 'visitor' in F#

let rec visitor dir filter= 
    seq { yield! Directory.GetFiles(dir, filter)
          for subdir in Directory.GetDirectories(dir) do yield! visitor subdir filter} 

最近,我开始着手在C#中实现某些F#功能,并且我试图将其重现为IEnumerable,但是我很难做到除此以外的其他功能:

Recently I've started working on implementing some F# functionality in C#, and I'm trying to reproduce this as IEnumerable, but I'm having difficulty getting any further than this:

static IEnumerable<string> Visitor(string root, string filter)
{
    foreach (var file in Directory.GetFiles(root, filter))
        yield return file;
    foreach (var subdir in Directory.GetDirectories(root))
        foreach (var file in Visitor(subdir, filter))
            yield return file;
}

我不明白的是为什么我必须在C#版本中进行两次foreach递归,而在F#中却没有... seq {}是否隐式地执行"concat"操作?

What I don't understand is why I have to do a double foreach in the C# version for the recursion, but not in F#... Does the seq {} implicitly do a 'concat'?

推荐答案

yield!执行展平"操作,因此它将传递给它的序列集成到外部序列中,对序列和每个序列上的yield.

yield! does a 'flatten' operation, so it integrates the sequence you passed it into the outer sequence, implicitly performing a foreach over each element of the sequence and yield on each one.

这篇关于用C#编写F#递归文件夹访问者-seq vs IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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