lua-users home
lua-l archive

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


-- try this to get tail call
function sumofn( sum, x, ... )
	if not x then return sum end
	return sumofn( sum + x, ... )
end

-- or the 5.0 version
function sumofn( sum, x, ... )
	if not x then return sum end
	return sumofn( sum + x, unpack(arg) )
end

But for this I would use the for-loop..

Asko Kauppi wrote:

Going for it myself:

-- Returns the sum of all given values (using tail recursion)
--
function sumofn( a,b, ... )
--return b and sumofn(a+b,...) or a or 0 -- not proper tail call (but works)
    return (not b) and (a or 0) or sumofn(a+b,...)    -- proper tail call
end


Since the above wasn't proper tail calls after all (acording to Roberto)