archives

Lambda in C# 3.0

Maybe on the edge of being off-topic, but I figure that since this place is called Lambda-the-Ultimate, perhaps questions about lambda in evolving languages might be tolerated.

I've been hearing that the next-gen of C# was supposed to add support for lambdas, so I downloaded the beta. Starting out, it looks rather hopeful.

delegate int IntToInt(int i);

static IntToInt Factorial = 
    (n) => n <= 1 ? 1 : n * Factorial(n - 1);

First inconvenience is that I have to declare delegates that match the signature of any lambda functions I want to assign. Wonders if it's possible to do this without having to declare a delegate?

More inconvenient is that recursion only works for static declarations. The following is fairly identical to the above, other than the fact that it is an instance variable, but will not compile:

delegate int IntToInt(int i);

IntToInt Factorial = 
    (n) => n <= 1 ? 1 : n * Factorial(n - 1);

So I'm wondering how one goes about getting recursive functions using the lambda syntax? ML does this with the 'rec' attribute keyword but I don't find anything similar in the new C# specs.

My own opinion is that there should not be a distinction between named and anonymous functions, though a lot of languages I encounter seem to make this distinction. C# 3.0 doesn't have Python's limitation of being restricted to expressions - control structures can be used:

static IntToInt Factorial = 
    (n) =>
    { 
        if (n <= 1) 
            return 1; 
        else 
            return n * Factorial(n - 1); 
    };

Nor does it require special application like Ruby's call. But it does seem to have rules about forbidding the reuse of parameter names that are in the scope of the defining body (if X is declared in the surrounding scope, then X can't be a parameter for the lambda function).

I'm guessing that the main impetus for lambdas in C# is the new DLinq syntax, so perhaps assigning lambdas to variables in trying to create blocked scoped functions is not a priority.