lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, Aug 10, 2008 at 7:29 PM, Vyacheslav Egorov <mister.aleph@gmail.com> wrote:
> The problem to me is the syntax
Syntax is not a problem. Just use metalua :)

I think the main "problem" here, besides anonymous function verbosity,  is that we expect loop bodies to be the last part of an idiom. Closing parentheses, and even worse list argument name, after the function used as a loop body are painfully unidiomatic:

   map (function (e)
       return e
    end, list)

There's a pretty old fix in metalua for short anonymous functions, which works well in practice: "function(x, y, z) return x+y+z end" can be abbreviated "|x,y,z| x+y+z".

For the loop body position issue, I think that Haskell's "where" operator would do great:

   squares = map (sqr, {1, 2, 3, 4, 5}) where function sqr(x)
      return x*x
   end

Or in this case, with short lambdas:

   squares = map (sqr, {1, 2, 3, 4, 5}) where sqr = |x| x*x

"foo where bar=baz" makes the local assignment "bar=baz" valid during the evaluation of "foo".
The "where function bar() ... end" additional syntax sugar is the straightforward adaptation of plain Lua's "local function bar() ... end".

Notice that this idiom incites to give a self-documenting name to the body, which is a Good Thing. Of course, nothing prevents you from simply calling it "f".

Untested metalua extension code to implement the "where" syntax:

   mlp.lexer:add 'where'

   mlp.expr.suffix:add {
      "where", gg.multisequence {
         -- "expr where function foo(x) ... end":
         { "function", mlp.id, mlp.func_val, builder = |x| `Localrec{ {x[1]}, {x[2]} } },
         -- "expr where a, b, c = 1, 2, 3":

         default = { mlp.id_list, "=", mlp.expr_list, builder = 'Local' } },
      builder = |e, s| `Stat{ s, e } }


-- Fabien.