Herly Quijano
Newcomer
- Joined
- Mar 19, 2021
- Messages
- 75
- Reaction score
- 9
I wanna add recursion to anonymus functions, is there a way to do that? like a keyword or a process or yes or yes must have a name?
Y = function (f)
local g = function (x) return f ( x (x)) end
return g(g)
end
function fact (n)
return (n<2) and n or n*fact(n-1) end
print (fact(4)) --> 24
local Y = function (g)
return (function (f)
f = g ( function (x) return (f (x)) end)
return f end) end
local F = function (f) return function (n)
return (n<2) and n or n*f(n-1) end end
print (Y(F)(4)) --> 24
function: 00000<Always a different "code">
No, I want but without naming the function.It looks like my first suggestion does not work. I think what you are asking for is how to do a calculation like
(function (g) return (
function (f) f = g ( function (x) return (f (x)) end)
return f end) end ) ( function (h) return function (n)
return (n<2) and n or n*h(n-1) end end)
-- func is a function that needs a function as parameter, what it does is irrelevant
func(function (x)
if Cond then
(Call this function again)(x)
end
end)
local function f(x)
if Cond then f(x) end
end
func(f)
Y
combinator as given above provides a means of doing this. Its crucial property is that Y(f)
reduces to f(Y(f))
- the fixed-point property. Using it makes it possible to rewrite definitions without explicit recursion. Thus, in the remarks above, Y(F)
does the same as fact
. You get F
from fact
by replacing the repeated variable of the recursion by a new variable, and this works quite generally. However, as stetre says, why should you want to do this?local f
function f(x) if Cond then f(x) end end
NB. Should that not be? I always use the unsugared syntax for functions so I am not quite sure how the rule about locality starting on the next line plays out here.Lua:local f function f(x) if Cond then f(x) end end
local f = function(x) if Cond then f(x) end end -- doesn't work: f is nil inside the body
func(f)
local f
f = function(x) if Cond then f(x) end end
func(f)