从基础概念解释“伪”递归

=========================

Func<int, int> fac = null;
fac = x => x <= 1 ? 1 : x * fac(x - 1);
Console.WriteLine(fac(5)); // 120;

Func<int, int> facAlias = fac;
fac = x => x;
Console.WriteLine(facAlias(5)); // 20

第一次打印出的120是正确的结果。不过facAlias从fac那里“接过”了使用Lambda表达式构造的委托对象之后，我们让fac引用指向了新的匿名方法x => x。于是facAlias在调用时：

facAlias(5)     <— facAlias是x => x <= 1 ? 1 : x * fac(x – 1)
= 5 <= 1 ? 1 : 5 * fac(5 - 1)
= 5 * fac(4)    <— 注意此时fac是x => x
= 5 * 4
= 20

自然就不对了。

=============================

==================================

public static Func<int, int> Fibonacci = n => n > 1 ? Fibonacci(n - 1) + Fibonacci(n - 2) : n;

Func<int, int> Fibonacci = null;
Fibonacci = n => n > 1 ? Fibonacci(n - 1) + Fibonacci(n - 2) : n;

===================================

Func<int, int> fac = null;

fac = x => x <= 1 ? 1 : x * fac(x - 1);

Func<int, int> facAlias = fac;

fac = x => x;

Console.WriteLine(facAlias(5)); // 20

facAlias(5) <— facAlias是x => x <= 1 ? 1 : x * fac(x – 1)

= 5 <= 1 ? 1 : 5 * fac(5 - 1)

= 5 * fac(4) <— 注意此时fac是x => x

= 5 * 4

= 20

Func<int, int> fac = null;

fac = x => x <= 1 ? 1 : x * fac(x - 1);

=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

posted @ 2009-09-02 10:13  徐少侠  阅读(2108)  评论(17编辑  收藏