问题
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);
}
回答1:
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);
}
回答2:
Like Justice said, you can do it with C# 3.5 and lambdas; if you have C# 2.0, you can use anonymous functions, although it would be somewhat less sexy:
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);
}
Edit: I forgot, Func isn't defined in C# 2.0, so you have to define it yourself:
public delegate TResult Func<T, TResult>(T guess);
来源:https://stackoverflow.com/questions/576374/why-doesnt-c-sharp-have-lexically-nested-functions