[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
**Subject**: **Anonymous recursion**
**From**: Reuben Thomas <rrt1001@...>
**Date**: Thu, 4 Jan 2001 11:57:55 +0000 (GMT)

If you look in tests/factorial.lua, you'll find an implementation of the Y
combinator that lets you make an arbitrary function recursive. The idea is
that you take your ordinary version of the function:
f = function (...) ... f(...) ... f(...) ... end
and wrap it up:
F = function (f)
return function (...) ... %f(...) ... %f(...) ... end
end
replacing the recursive calls by calls to the upvariable %f, which is a
parameter to the new F.
You then say
f = Y(F)
and lo! f is now a recursive function. Of course, you can do the whole lot
in one step:
local f = Y(function ... end)
Because lua is not a proper functional language, the definition of Y is even
hairier than usual, and to be honest, I haven't quite understood it myself,
although essentially, it turns F into F(Y(F)).
--
http://sc3d.org/rrt/
L'art des vers est de transformer en beautés les faiblesses (Aragon)