lua-users home
lua-l archive

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


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)