Lambda表达式编写递归函数
class Program
{
//Fix求出的是函数f的不动点,它就是我们所需要的递归函数:
static Func<T, TResult> Fix<T, TResult>(Func<Func<T, TResult>, Func<T, TResult>> f)
{
return x => f(Fix(f))(x);
}
static Func<T1, T2, TResult> Fix<T1, T2, TResult>(Func<Func<T1, T2, TResult>, Func<T1, T2, TResult>> f)
{
return (x, y) => f(Fix(f))(x, y);
}
static void Main(string[] args)
{
//最大公约数
var fac = Fix<int, int>(f => x => x <= 1 ? 1 : x * f(x - 1));
//fibonacci数列
var fib = Fix<int, int>(f => x => x <= 1 ? 1 : f(x - 1) + f(x - 2));
//阶乘
var gcd = Fix<int, int, int>(f => (x, y) => y == 0 ? x : f(y, x % y));
//函数式链表快速排序
var qsort = Fix<IEnumerable<int>, IEnumerable<int>>(f => l => l.Any() ? f(l.Skip(1).Where(e => e < l.First())).Concat(Enumerable.Repeat(l.First(), 1)).Concat(f(l.Skip(1).Where(e => e >= l.First()))) : Enumerable.Empty<int>());
Console.WriteLine(gcd(10, 8));
Console.WriteLine(fib(10));
Console.WriteLine(fac(5));
List<int> lTest = new List<int>();
lTest.AddRange(new int[] { 4,5,1,23,3,43,8,7,1});
foreach (int item in qsort(lTest))
{
Console.WriteLine(item);
}
Console.Read();
}
}
更详细的去看:
http://www.cnblogs.com/JeffreyZhao/archive/2009/08/31/recursive-lambda-expressions.html