Lambda vs. function

David-Sarah Hopwood david.hopwood at industrial-designers.co.uk
Tue Oct 28 11:03:32 PDT 2008


Breton Slivka wrote:
[...]
> var dispatch = {
>     1: lambda () {
>             p() ?  f(), g() : dispatch[2]();
>     },

I'm nitpicking, but this is invalid syntax -- due to the relative
precedence of comma and ?:, it will be parsed as:

  (p() ? f()), (g() : dispatch[2]());

You want something like

  p() ? lambda {f(); g();}() : dispatch[2]();

(I'm using Mark Miller's proposed syntax for lambda.)

> I've used tertiary operators to replace if/else, since the tertiary
> operator is an expression form where the tail position is rather
> obvious and defined. (i think).  If there's a lambdified version of
> the if/else statement, or "while", I would be fascinated.

if/else can be desugared to ?: like this:

  if (cond) { thenClause } else { elseClause }
==>
  (cond) ? lambda { thenClause }() : lambda { elseClause }()

  if (cond) { thenClause }
==>
  (cond) ? lambda { thenClause }() : undefined

Note that the tail statement in the selected arm automatically gives
the result of the 'if', i.e. this turns the whole 'if/else' into an
expression, which is what we want in the case where it is the tail
statement of a lambda. In your example, if switcher is 1 and p() is
true, then this expansion will make the whole 'switch' evaluate to g().

Ignoring 'break' and 'continue', 'while' can be desugared using
tail recursion like this:

  while (cond) { body }
==>
  lambda $loop { if (cond) { { body } $loop(); }();

Here the 'while' statement always evaluates to 'undefined' (when it
terminates), which is probably a good idea since there may be zero
iterations.

-- 
David-Sarah Hopwood


More information about the Es-discuss mailing list