public delegate Func<A, R> Recursive<A, R>(Recursive<A, R> r)
public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f) {
Recursive<A, R> rec = r => a => f(r(r))(a);
return rec(rec);
}
I used it to recursively get all the files in a given directory, in a one-liner:
var RecGetFiles = Y<string, IEnumerable<string>>(f => d => Directory.GetFiles(d).Concat(Directory.GetDirectories(d).SelectMany(f)))Nice, isn't it? Sample usage:
foreach (var f in RecGetFiles(Directory.GetCurrentDirectory()))
Console.WriteLine(f);
It's probably not a good idea, though, to use this in production code, as it's not really necessary (just use regular recursion) and it harms readability.
Excellent example! Thanks for doing this.
ReplyDelete