看了你的代码才知道Lambda表达式是支持多行代码的.
这个情况下,匿名代码能写的, Lambda当然也能写.
因为这种连多条statement都能写的Lambda,
已经彻底是匿名方法的简写版了.
或者说,要讨论的话题已经模糊了.
到底是Lambda表达式写法是否优越的讨论,
还是函数式编程的讨论.还是语言写法的讨论???
要知道f => x => x > 2 ? f(x - 1) + f(x - 2) : 1 这里,
f 不是 "x => x > 2 ? f(x - 1) + f(x - 2) : 1".
这个写法本身就不是递归.
只不过是在Fix中采取特殊方法,
生成一个f去调用"x => x > 2 ? f(x - 1) + f(x - 2) : 1"
产生递归的效果.
所以这个写法和下面的做法完全不同:
Func<int, int> Feb = null;
Feb = delegate(int n)
{
if (n > 2)
return Feb(n - 1) + Feb(n - 2);
return 1;
};
或者换成Lambda写法
Func<int, int> Feb = null;
Feb = n => n > 2 ? Feb(n - 1) + Feb(n - 2) : 1;
可以看出.这个才是真正的递归.
其实定义 Func<int, int> Feb = null; 是迫不得已的.
直接写 Func<int, int> Feb = n => n > 2 ? Feb(n - 1) + Feb(n - 2) : 1;
的话, C#会提示Feb是未赋值的.
我已经不知道自己想讨论什么了.
只希望把目前还比较清晰的想法写出来看看.
另外附带一个匿名函数递归用法的例子:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
List<string> errorlist = new List<string>();
Action<string> ScanDirectory = null;
ScanDirectory = delegate(string dir)
{
list.Add(dir);
string[] subdirs;
try
{
subdirs = Directory.GetDirectories(dir);
}
catch (UnauthorizedAccessException)
{
errorlist.Add(dir);
return;
}
foreach (string subdir in subdirs)
{
ScanDirectory(subdir);
}
};
string root = "C:\\Program Files\\Common Files\\Microsoft Shared";
ScanDirectory(root);
foreach (string dir in list)
{
Console.WriteLine(dir.Remove(0, root.Length));
}
Console.WriteLine(list.Count + " , " + errorlist.Count);
}
}
}
回复 引用