lua-users home
lua-l archive

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



local function Y(f)
local function g(...) return f(g, ...) end
return g
end

print(Y(function(fac, n) if n <= 1 then return 1 else return n*fac(n-1) end end)(10))


There's a more complicated version of Y that does not require an assignment (local function g(...)  is really local g; g = function(...))

On Sun, Sep 9, 2018 at 6:24 PM Sean Conner <sean@conman.org> wrote:
It was thus said that the Great Sam Pagenkopf once stated:
> The recursive definitions are something I didn't consider. If you were to
> enable recursion in local function assignments. it would be strange because
> it violates scoping rules.

  Nope, not with the Y-combinator:

        local fact = Y(function(self,n)
          if n == 0 then
            return 1
          else
            return n * self(n - 1)
          end
        end)

        print(fact(5))

  Now the trick is to define Y().

  -spc




--
--