lua-users home
lua-l archive

Re: Recursive anonymous functions?

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


On 22-Jul-04, at 9:31 PM, Gabor Grothendieck wrote:
For example, we can invoke the anonymous factorial function
evaluating it for the argument 3 like this:
 Recall = function(...)
 return debug.getinfo(2,"f").func(unpack(arg))
 end
The use of the debug library is not advisable, unless you are actually debugging. Furthermore, this will not work on the tail-recursive implementation of factorial:
print ((function(x, acc)
 if x <= 1 then return acc
 else return Recall(x - 1, x * acc)
 end
 end) (3, 1))
stdin:1: attempt to call field `func' (a nil value)
stack traceback:
 stdin:1: in function `Recall'
 (tail call): ?
 stdin:5: in main chunk
 [C]: ?
---------- Just to confirm:
do
 local function fact(x, acc)
 if x <= 1 then return acc
 else return fact(x - 1, x * acc)
 end
 end
 for i = 1, 10 do print(fact(i, 1)) end
end
==>
1
2
6
24
120
720
5040
40320
362880
3628800

AltStyle によって変換されたページ (->オリジナル) /