I have an example of some similar code that is not an exact recursive delegate, but it is close. "Y-Combinator" is close - and to be honest, I have no idea how this works in practice, but it is used to define recursive functions.
Here is the funky code you need to define:
public delegate T S<T>(S<T> s); public static T U<T>(S<T> s) { return s(s); } public static Func<A, Z> Y<A, Z>(Func<Func<A, Z>, Func<A, Z>> f) { return U<Func<A, Z>>(r => a => f(U(r))(a)); }
Now you can define recursive functions in one line.
Factorial:
var fact = Y<int, int>(_ => x => x == 0 ? 1 : x * _(x - 1)); var fact5 = fact(5);
Fibonacci:
var fibo = Y<int, int>(_ => x => x <= 1 ? 1 : _(x - 1) + _(x - 2)); var fibo5 = fibo(5); // == 8 var fibo6 = fibo(6); // == 13 var fibo7 = fibo(7); // == 21
My favorite line of code is calling s(s) . Seriously, if someone can straighten it out of their heads, they are a genius! Not to mention the whole U<Func<A, Z>>(r => a => f(U(r))(a)) .
source share