lua-users home
lua-l archive

Re: Self-awareness of functions?

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


On 30 December 2010 01:22, Steve Litt <slitt@troubleshooters.com> wrote:
> On Thursday 30 December 2010 00:44:22 Henk Boom wrote:
>
>> function recursify(f)
>>   local function g(...)
>>     return f(g, ...)
>>   end
>>   return g
>> end
>>
>> fact = recursify(function (self, n)
>>   if n == 1 then
>>     return 1
>>   else
>>     return n * self(n-1)
>>   end
>> end)
>
> One of the seven wonders of the world is that Lua actually makes that work. I
> can almost, but not quite wrap my head around it. Tomorrow's another day.
>
> Henk -- by what mental process did you devise this solution?
I remembered that you can define a recursive function without mutation
by passing it to itself as a parameter
local fact2 = function (recur, n)
 if n == 1 then return 1 else return n * recur(recur, n-1) end
end
local fact = function (n)
 return fact2(fact2, n)
end
After that it was just a matter of turning the pattern above into a
general higher-order function, and adding some sugar so that you don't
need to explicitly pass the function to itself in the recursive call.
 henk

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