为什么C#语言设计师可能没有包含对此类内容的支持(移植自Structure and Interpretation of Computer Programs,第二版,第30页):
/// <summary>Return the square root of x.</summary>
double sqrt(double x) {
bool goodEnough(double guess) {
return Math.Abs(square(guess) - x) < 0.001;
}
double improve(double guess) {
return average(guess, x / guess);
}
double sqrtIter(double guess) {
return goodEnough(guess) ? guess : sqrtIter(improve(guess));
}
sqrtIter(1.0);
}
答案 0 :(得分:36)
事实上,C#就是这样。
double sqrt(double x) {
var goodEnough = new Func<double, bool>(guess =>
Math.Abs(square(guess) - x) < 0.001
);
var improve = new Func<double, double>(guess =>
average(guess, x / guess)
);
var sqrtIter = default(Func<double, double>);
sqrtIter = new Func<double, double>(guess =>
goodEnough(guess) ? guess : sqrtIter(improve(guess))
);
return sqrtIter(1.0);
}
答案 1 :(得分:8)
正如Justice所说,你可以用C#3.5和lambdas来做;如果你有C#2.0,你可以使用匿名函数,虽然它不那么性感:
double sqrt(double x) {
Func<double, bool> goodEnough = delegate(double guess) {
return Math.Abs(square(guess) - x) < 0.001;
};
Func<double, double> improve = delegate(double guess) {
return average(guess, x / guess);
};
Func<double, double> 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, TResult>(T guess);