lua-users home
lua-l archive

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


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)

More universal implementation would allow both functions and
booleans/others:

function choose(cond, yescase, nocase)
  if cond then
    if type(yescase)=='function' then
      return yescase()
    else
      return yescase
    end
  else
    if type(nocase)=='function' then
      return nocase()
    else
      return nocase
    end
  end
end

print (choose(false, yesfunction, 'Hello'))

So you no longer need a change in the language syntax.

Regards,
miko