This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
H4X0RZ's profile picture

"Recursion without names and loops"

Started by H4X0RZ, 12 August 2016 - 05:36 PM
H4X0RZ #1
Posted 12 August 2016 - 07:36 PM
I found an article about "Recursion without names and loops" (can't find it anymore) and I tried to port this (IMO really awesome) function over to lua.
The function will calculate the factorial of a given number.

This is the result:

(function(f) return f(f) end)(function(func) return function(n) return n == 0 and 1 or (n*func(func)(n-1)) end end)

SpoilerYou use it like this:

local factorialOf10 = (function(f) return f(f) end)(function(func) return function(n) return n == 0 and 1 or (n*func(func)(n-1)) end end)(10)

Maybe this is new to someone so I decided to share this with our awesome comunity. I hope that some Lua wizard will find this and invent something interesting with it xD
SquidDev #2
Posted 12 August 2016 - 09:51 PM
For those interested this is known as the Fixed-point combinator. There are also versions for mutual recursion. A fun thing to do is to expand the function out by hand to see how it works.