为什么C#没有词汇嵌套函数? [英] Why doesn't C# have lexically nested functions?
本文介绍了为什么C#没有词汇嵌套函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么C#语言设计人员可能不包括对类似内容的支持(源自计算机程序的结构和解释,第二版,第30页):
Why might the C# language designers not have included support for something like this (ported from Structure and Interpretation of Computer Programs, second ed., p. 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);
}
推荐答案
事实上,C#确实有这个.
In fact, C# has exactly this.
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);
}
这篇关于为什么C#没有词汇嵌套函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文