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

查看:9
本文介绍了在 C# 中编写 F# 递归文件夹访问者 - seq 与 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! 执行展平"操作,因此它将您传递给它的序列集成到外部序列中,隐式执行 foreach 在序列的每个元素上,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 与 IEnumerable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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