C# lambda递归

这个不是我发明的,只是拿来人脑运行一下,有点烧脑。

 1   public class Recursive
 2     {
 3         delegate T SelfApplicable<T>(SelfApplicable<T> self);
 4 
 5         public static void Run()
 6         {
 7             // The Y combinator
 8             SelfApplicable<Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>>> Y =
 9                 y =>
10                     f =>
11                         x => f(y(y)(f))(x);
12             
13             // The fixed point generator
14             Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>> Fix = Y(Y);
15 
16             // The higher order function describing factorial
17             Func<Func<int, int>, Func<int, int>> F =
18                 fac =>
19                     x =>
20                         x == 0 ?
21                             1 :
22                             x * fac(x - 1);
23 
24             // The factorial function itself
25             Func<int, int> factorial = Fix(F);
26 
27             Console.WriteLine(factorial(10));
28 
29         }
30 
31     }

F == fac => x => x == 0 ? 1 : x * fac(x-1)
Y == y=>f=>x=>f(y(y)(f))(x)
Y(Y) == f=>x=>f(Y(Y)(f))(x)
Y(Y)(F) == x=>F(Y(Y)(F))(x)
Y(Y)(F)(10) == F(Y(Y)(F))(10)         A:递归开始的地方
      == F((f=>x=>f(Y(Y)(f))(x))(F))(10)
      == F(x=>F(Y(Y)(F))(x))(10)
      == (fac=>x=>x==0?1:x*fac(x-1))(x=>F(Y(Y)(F))(x))(10)
      == (x=>x==0?1:x*(x=>F(Y(Y)(F))(x))(x-1))(10)
      == 10==0?1:10*(x=>F(Y(Y)(F))(x))(10-1)
      == 10*(x=>F(Y(Y)(F))(x))(9)
      == 10*F(Y(Y)(F))(9)        B: 就像A,又一次开始
      == .......
      ..........
      == 10*9*8*7*6*5*4*3*2*1*F(Y(Y)(F))(0)
      == 10*9*8*7*6*5*4*3*2*1*F((f=>x=>f(Y(Y)(f))(x))(F))(0)
      == 10*9*8*7*6*5*4*3*2*1*F(x=>F(Y(Y)(F))(x))(0)
      == 10*9*8*7*6*5*4*3*2*1*(fac=>x=>x==0?1:x*fac(x-1))(x=>F(Y(Y)(F))(x))(0)
      == 10*9*8*7*6*5*4*3*2*1*(x=>x==0?1:x*(x=>F(Y(Y)(F))(x))(x-1))(0)
      == 10*9*8*7*6*5*4*3*2*1*(0==0?1:0*(x=>F(Y(Y)(F))(x))(0-1))
      == 10*9*8*7*6*5*4*3*2*1*1

 

好美......

So beautiful......

终极感受:

  

1 new Func<int, int>(i =>
2                 new Func<Func<int, int>, Func<int, int>>(fac => x => x == 0 ? 1 : x * fac(x - 1))(
3                     new SelfApplicable<Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>>>(
4                         y => f => x => f(y(y)(f))(x)
5                     )(
6                         y => f => x => f(y(y)(f))(x)
7                     )(
8                         fac => x => x == 0 ? 1 : x * fac(x - 1))
9                     )(i))(10)

No function Name,No trouble.

posted @ 2015-12-15 23:13  LeonGo  阅读(1613)  评论(0编辑  收藏  举报