Here is an answer similar to the one provided by @hvd, but using the Y operator defined here , this eliminates the need for local variables:
public static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f) { return t => f(Y(f))(t); } var halves = Y<double, IEnumerable<double>>(self => d => new[] { 0d }.SelectMany(_ => new[] { d }.Concat(self(d / 2))));
Usage example:
foreach (var half in halves(20)) Console.WriteLine(half);
What will output 20, 10, 5, 2.5, etc.
I would not recommend using this in production code, but it's fun.
The Y operator also allows other recursive lambda expressions, for example:
var fibonacci = Y<int, int>(self => n => n > 1 ? self(n - 1) + self(n - 2) : n); var factorial = Y<int, int>(self => n => n > 1 ? n * self(n - 1) : n); var hanoi = Y<int, int>(self => n => n == 1 ? 1 : 2 * self(n - 1) + 1);
Lukazoid
source share