Semantics and abstract syntax of lambdas

Yuh-Ruey Chen maian330 at gmail.com
Wed Dec 17 18:42:44 PST 2008


Lex Spoon wrote:
> On Mon, Dec 8, 2008 at 4:08 AM, Yuh-Ruey Chen <maian330 at gmail.com> wrote:
> > Jon Zeppieri wrote:
> >> So, unless people want to expand the expression grammar significantly,
> >> I think the expression body is a nonstarter.
> >>
> >
> > How feasible would it be to make JS a pure expression language? That is,
> > can the language be modified to allow things like:
> >
> > x = if (a)
> >    b;
> > else
> >    c;
> >
> > first_test_prop = for (let p in o)
> >    if (/^test/.test(p)/) {
> >        p; break;
> >    }
>
> There's a simpler way to expand the expression language dramatically.
> I'm not sure why so few languages include it, and I'd be curious if it
> has been considered for Harmony.
>
> The technique is to include an expression form which contains a
> sequence of statements followed by an expression.  In Scala, the
> syntax looks like this:
>
>    { statement1; statement2; result_expression }
>
> So you can do things like:
>
>   { val x = 1; val y = 2; x+y }
>
> The result would be 3.  I'm not sure what the best syntax would be for
> JavaScript, but surely there is room somewhere.
>   

Unfortunately, "{" in expression context is taken by the object literal.
However, I think "{{" would be feasible. That is, if the parser is in
the expression context, if it encounters two '{' tokens in a row, it
could treat it as you defined above, e.g.

val = {{ val x = 1; val y = 2; x + y }}

> A light syntax for this kind of expression would immediately solve the
> issue with lambdas that result in expressions.  This, in turn,
> honestly seems important for lambdas to really be convenient to use.
> (Granted, lambdas being convenient is much less important than having
> them available at all.)
>   

Do you have an explicit syntax in mind?

I can turn this around and say that with really convenient lambdas,
expressions of the form you discuss would be trivial, e.g.

val = fn { val x = 1; val y = 2; x + y }()

> There are side benefits to this expression form, too.  It means you
> can much more frequently replace a function call by the function's
> contents, even when the function appears in an expression-only
> context.  For example, you can more frequently inline the g() in
> f(g()).  This makes programmers more dextrous, because their rewrites
> can be more localized.  Further, it has obvious application for an
> optimizing compiler such as GWT's....
>   

Very true, and one of the reasons I dislike the distinction between
statements and expressions.


More information about the Es-discuss mailing list