lua-users home
lua-l archive

Re: Recursive anonymous functions?

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


Philip Bock <phil <at> flamewars.org> writes:
> Is there any way for an anonymous function to call itself?
It seems your problem can be answered without addressing the
literal question you asked but just for the sake of
completing this, we could use fixed point combinator ideas
from computer science to create anonymous recursive
functions.
Try this:
1. define this utility function:
 Y = function(f) return f(f) end
2. define an anonymous function which is a function with
 argument f, say, that returns a function that is the same as
 the factorial function except that f(f) is written in place
 of the recursive function call. 
3. pass the anonymous function in #2 to Y. Y takes #2
 as an input and outputs the desired recursive factorial
 function.
For example,
 Y = function(f) return f(f) end
 print(Y(function(f)
 return function(n) 
 if (n == 0) then
 return 1
 else
 return n * f(f)(n-1)
 end
 end
 end)(3))
will print 3 factorial which is 6.
For more on this, check out
 http://okmij.org/ftp/Computation/fixed-point-combinators.html
and google for fixed point combinator for even more.
I know of one language that has a built in Recall function that 
will recursively call the function its called in to make it
easier to write anonymous recusrive functions. I don't think Lua 
has such a facility but if it does someone might be able to point it 
out.

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