事实上,C#就是这样.
double sqrt(double x) { var goodEnough = new Func(guess => Math.Abs(square(guess) - x) < 0.001 ); var improve = new Func (guess => average(guess, x / guess) ); var sqrtIter = default(Func ); sqrtIter = new Func (guess => goodEnough(guess) ? guess : sqrtIter(improve(guess)) ); return sqrtIter(1.0); }
就像Justice说的那样,你可以用C#3.5和lambdas做到这一点; 如果你有C#2.0,你可以使用匿名函数,虽然它会不那么性感:
double sqrt(double x) { FuncgoodEnough = delegate(double guess) { return Math.Abs(square(guess) - x) < 0.001; }; Func improve = delegate(double guess) { return average(guess, x / guess); }; Func sqrtIter = null; sqrtIter = delegate(double guess) { return goodEnough(guess) ? guess : sqrtIter(improve(guess)); }; return sqrtIter(1.0); }
编辑:我忘了,Func没有在C#2.0中定义,所以你必须自己定义:
public delegate TResult Func(T guess);