Why doesn't C# have lexically nested functions?

北城以北 提交于 2019-12-30 01:08:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!