lua-users home
lua-l archive

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


Imagining we could define no argument anonymous functions like:

local i;
local fn = [i=0; return y];

We could use the choose function like so:

local myvar=choose(expr, [return x], [return y])

Which to some might still look ugly. ("Whats with the line noise?") etc...

So how about a syntax to define functions with arguments that are lazily evaluated?

function choose(expr, [x], [y])
	-- x and y are functions that must be called to get their value.
	if expr return x() else return y() end
end

usage:
local myvar = choose(i==1, false, true)

Voila, a semi-lazy function.

Eric

On 16/09/2010, at 7:10 PM, Michal Kottman wrote:

On Thu, 2010-09-16 at 10:41 +0200, Michal Kolodziejczyk wrote:
On 16.09.2010 09:48, David Kastrup wrote:
Jeff Pohlmeyer <yetanothergeek@gmail.com> writes:

On Thu, Sep 16, 2010 at 2:20 AM, steve donovan wrote:

Just to be different, how about a pseudo-function
choose(cond,val1,val2) with the appropriate lazy evaluation?

pseudo?

function choose(expr,yes,no)
 if expr then return yes else return no end
end

That evaluation is inappropriately unlazy.

Right, it should call functions at check time, like this:

function choose(cond, yesfunction, nofunction)
 if cond then
   return yesfunction()
 else
   return nofunction()
 end
end

But then it should be called like:
choose(true, function() print('YES') end, function() print('NO') end)
or in general case:
choose(cond, yesfunction, nofunction)

Here, a syntax for short anonymous functions a-la RiscLua (\ and =>) or
Metalua (|x,y| x+y for function(x,y) return x+y end) would help. "Lazy
expressions" could be written as simple anonymous functions, and
choose() would be a normal Lua function (i.e. no "special" part of the
Lua grammar). The code could look like:

local x, y, z
z = choose(y~=0, || x/y, || 0)

However, the syntax sugar for anonymous functions has also been
discussed on this list before (and rejected, AFAIK).