lua-users home
lua-l archive

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


2011/7/1 steve donovan <steve.j.donovan@gmail.com>:
> On Fri, Jul 1, 2011 at 12:36 PM, Jerome Vuarand
> <jerome.vuarand@gmail.com> wrote:
>> I understand that this "by-name" mechanism requires the compiler to
>> know the callee prototype at the caller site,
>
> Also, the programmer needs to know the prototype ;)  I'm thinking here
> of C++ reference parameters, which are less obvious than the old C
> pass-a-pointer method. C# actually has a keyword 'ref' to make such
> parameters stand out more.
>
> So, assuming a list object that can be filtered, we could ask for a
> list of all positive elements like so:
>
> lpos = ls:filter(lazy _ > 0)
>
> where lazy <expr> is short for function(_) return <expr> end
>
> Having an explicit keyword/macro/whatever 'lazy' feels better than an
> implicit quoting for arguments to this kind of function.

The problem with a single keyword is that you have no end delimiter,
and therefore you cannot return multiple values, but maybe that's nice
enough.

I think a goal for all that lazy stuff, would be to allow programmers
use Lua in more functional style, while keeping its simple syntax. For
example it would be nice to be able to write:

  local x = 0
  mywhile x < 10 do
    x = x + 1
    print(x)
  end

Let's dream a bit. With 1. your lazy keyword proposal, 2. a "do end"
short syntax for "function() end", and 3. the ability to avoid
parenthesis around "do end" lambda constructors like it is already the
case for table and string constructors (but that would introduce
ambiguities in current syntax), we could get:

  local x = 0
  mywhile (lazy x < 10) do
    x = x + 1
    print(x)
  end

which is pretty close to the goal, with mywhile defined as:

  local function mywhile_helper(condition, action)
    if condition() then
      action()
      -- return for tail call optimization
      return mywhile_helper(condition, action)
    end
  end

  function mywhile(condition)
    return function(action)
      return mywhile_helper(condition, action)
    end
  end