# 如何写递归的 Lambda 表达式

Func<int, int> factorial = x => x == 0 ? 1 : x * factorial(x - 1);

Func<int, int> factorial = null;
factorial = x => x == 0 ? 1 : x * factorial(x - 1);


var f2 = factorial;
factorial = i => i;
Console.WriteLine(f2(5));


x => x == 0 ? 1 : x * (i => i)(x - 1)

## 函数映射函数（传说中的高阶函数？）

Func<Func<int, int>, int, int> factorial = ( fac, x ) => x == 0 ? 1 : x * fac(x - 1);

Func<Func<int, int>, Func<int, int>> map = fac => x => x == 0 ? 1 : x * fac(x - 1);


## 这个“人家”就是我们（传说中函数的固定点？）

map(Factorial) =
x => x == 0 ? 1 : x * Factorial(x - 1)


Factorial =
x => x == 0 ? 1 : x * Factorial(x - 1)


static Func<T, T> Fix<T>( Func<Func<T, T>, Func<T, T>> map )
{
// ...
}


static Func<T, T> Fix<T>( Func<Func<T, T>, Func<T, T>> map )
{
return Fix(map);
}


static Func<T, T> Fix<T>( Func<Func<T, T>, Func<T, T>> map )
{
return map(Fix(map));
}


static Func<T, T> Fix<T>( Func<Func<T, T>, Func<T, T>> map )
{
return x => map(Fix(map))(x);
}


## 总结

class Program
{
static void Main( string[] args )
{
Func<Func<int, int>, Func<int, int>> map
= fac => x => x == 0 ? 1 : x * fac(x - 1);

var factorial = Fix(map);

Console.WriteLine(factorial(5));
Console.ReadKey();
}

static Func<T, T> Fix<T>( Func<Func<T, T>, Func<T, T>> map )
{
return x => map(Fix(map))(x);
}
}


var factorial = map(Fix(map));


posted @ 2009-08-15 23:05 DiryBoy 阅读(...) 评论(...) 编辑 收藏