Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# have lexically nested functions?

Tags:

c#

scheme

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);
}
like image 943
Steve Betten Avatar asked Feb 23 '09 02:02

Steve Betten


People also ask

Why there is no string in C?

Both Java and Python have the concept of a "string", C does not have the concept of a "string". C has character arrays which can come in "read only" or manipulatable. A character array is a sequence of contiguous characters with a unique sentinel character at the end (normally a NULL terminator '\0' ).

What does C++ have that C doesnt?

C++ was developed by Bjarne Stroustrup in 1979. C does no support polymorphism, encapsulation, and inheritance which means that C does not support object oriented programming. C++ supports polymorphism, encapsulation, and inheritance because it is an object oriented programming language.

Why C has no exception handling?

As such, C programming does not provide direct support for error handling but being a system programming language, it provides you access at lower level in the form of return values. Most of the C or even Unix function calls return -1 or NULL in case of any error and set an error code errno.

Why is C not outdated?

The C programming language doesn't seem to have an expiration date. It's closeness to the hardware, great portability and deterministic usage of resources makes it ideal for low level development for such things as operating system kernels and embedded software.


1 Answers

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);
}
like image 110
yfeldblum Avatar answered Oct 05 '22 14:10

yfeldblum