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}
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; }
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!does a ‘flatten’ operation, so it integrates the sequence you passed it into the outer sequence, implicitly performing aforeachover each element of the sequence andyieldon each one.