lua-users home
lua-l archive

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


This was just a late-night musing, so you can just tell me I'm nuts. It
won't be the first time :-)

What if the semantics of varargs were changed so that instead of returning
a table constructed with the remaining arguments, it returned a binding
(curry) of the identity function with the remaining arguments? That is,

function foo(a, b, ...)
  -- do something
end

foo(2, 3, "A", "bunch", "of", "arguments")

Now, in the body of foo, a is bound to 2, b is bound to 3 and argfn (say)
is bound to:
function() return "A", "bunch", "of", "arguments" end

The current behaviour could be obtained by adding

local args = {argfn()}

as the first line of the function, so backwards compatibility is relatively
easy.

Now, instead of having to muck about with tinserts and call(), I can simply
use standard multiple-argument expansion:

function printf(file, fmt, ...) write(file, format(fmt, argfn())) end
-- The argument fmt is only provided for documentation purposes --

Or how about this:

function bindFrom2(fn, ...)
  return function(x) return fn(x, %argfn()) end
end

-- I suppose that the % would disappear in 4.1

To make this even more useful, it would be nice to be able to iterate over
the values in argfn. There are several possibilities, but an efficient
implementation of the following would handle many cases:

function mapargs(fn, first, ...)
   if first then return fn(first), mapargs(fn, argfn())
end

(That's a bit oversimplified, because it doesn't handle nil arguments. But
it has a certain couth to it. Of course, in a
non-optimised implementation, it would be somewhat inefficient.)

Since this is just a musing rather than a proposal, I haven't nailed down
all the details. It just seemed like an interesting idea. The concept is
that it is somewhat faster to construct a closure than a table, and much of
the time with varargs, you don't need (or even want) a table.

Rici

function