Expression closures - use-cases for shortcut lambda syntax (blocks)

Yuh-Ruey Chen maian330 at gmail.com
Sun Mar 18 06:34:50 PDT 2007


Vassily Gavrilyak wrote:
> I already proposed it.
>
> >>File.open("file", (file))=>{
> >>   //process
> >>});
> >>May be C# way will be good, and C# is ECMA too. It has the same
> superfluous () as ES3, >>but looks good.
>
> More examples from C# spec
> x => x + 1                                                      //
> Implicitly typed, expression body
> x => { return x + 1; }                  // Implicitly typed, statement body
> (int x) => x + 1                                        // Explicitly
> typed, expression body
> (int x) => { return x + 1; }    // Explicitly typed, statement body
> (x, y) => x * y                                 // Multiple parameters
> () => Console.WriteLine()               // No parameters
>   

I like it. As with any other syntax addition, I'd like the syntax to be
as universal as possible so as to make it intuitive. Since it's
equivalent to any other lambda syntax, it can be used within object
literals as well. Using all 3 lambda syntaxes:

obj = {
    x: 0,
    add: y => this.x + y,
    increment: y => void (this.x += y)
};

obj = {
    x: 0,
    add: function(y) { return this.x + y; },
    increment: function(y) { this.x += y; }
};

obj = {
    x: 0,
    add: function(y) this.x + y,
    increment: function(y) void (this.x += y)
};

For non-void functions, the a => b syntax looks really nice. Since it is
equivalent to function(a) b, I expect it to the have the same operator
precedence (higher than comma I think).

However, it can't be used for class methods, which I think is fine. But
if you really want the syntax to be as universal as possible, I can
imagine something like this:

class Klass {
    foo(x) => print(x)
}

or if parenthesis aren't required:

class Klass {
    foo x => print(x)
}

But that looks a bit to alien to me, since it's asymmetric with the call
syntax: we do o.foo(x), not o.foo x.

-Yuh-Ruey Chen



More information about the Es4-discuss mailing list