Sugar

Ingvar von Schoultz ingvar-v-s at comhem.se
Sat Aug 30 17:42:46 PDT 2008


YR Chen wrote:
> Ok, I'm really confused about the exact semantics of this new syntax. 
> Can you give explicit rules? As far as I can tell, this "sugar function" 
> can either desugar to a (const declaration + assignment + function call 
> + anonymous function) or just (function call + anonymous function), and 
> I'm not sure whether a specific sugar function usage desugars to the 
> former or the latter.

First, to give a simple rule, you can use these keywords just like
the |function| keyword. Similar syntax forms have similar meanings.
For example:

     use sugar Class;
     ...
     function Point (...) {...}
     Class Point (...) {...}

Here we have a Class declaration that looks just like a function
declaration -- it's in a statement position, not in an expression,
and there's a name before the "(". When a sugar keyword is used in
this way it binds the newly created function/class/constructor/etc
to the name.

Desugaring the above:

     const Point = Class (function Point (...) {...});

However:

     Pt = function Point (...) {...}
     Pt = Class Point (...) {...}

     Pt = function (...) {...}
     Pt = Class (...) {...}

Here we use the keyword in an expression, so that it returns the
newly created function/class/constructor/etc. Then if we write a
name before the "(" it's only internal.

Desugaring the above, in order:

     Pt = Class (function Point (...) {...});

     Pt = Class (function (...) {...});

However, just like any other function, a sugar keyword can have
very different meanings, depending on what the sugar-function
code does. Depending on the meaning, some of the above forms
may not make sense for a given keyword.

There's also a form that is not allowed with the |function| keyword
but can make perfect sense for a given sugar keyword. You can use
it in a statement position without a name before the "(":

     use sugar until;
     ...
     until (x > 42)
     {   ++x;
     }

The simplified desugaring that I showed in the thread starter can't
implement the above functionality. A more complete desugaring would be:

     until
     (   function() {return x > 42},
         function()
         {   ++x;
         }
     );

(But this is still simplified. For more, see other post.)

-- 
Ingvar von Schoultz



More information about the Es-discuss mailing list