about summary refs log tree commit diff stats
path: root/test/factorial.lua
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2021-10-19 21:38:48 -0700
committerKartik K. Agaram <vc@akkartik.com>2021-10-22 19:24:44 -0700
commit74f8cd15bb43110973deffdeb9dd229797e5b328 (patch)
tree12d6b5475a786eacf7a5a79b03b2b85621578ec6 /test/factorial.lua
downloadteliva-74f8cd15bb43110973deffdeb9dd229797e5b328.tar.gz
new fork of Lua 5.1
https://www.lua.org
Diffstat (limited to 'test/factorial.lua')
-rw-r--r--test/factorial.lua32
1 files changed, 32 insertions, 0 deletions
diff --git a/test/factorial.lua b/test/factorial.lua
new file mode 100644
index 0000000..7c4cf0f
--- /dev/null
+++ b/test/factorial.lua
@@ -0,0 +1,32 @@
+-- function closures are powerful
+
+-- traditional fixed-point operator from functional programming
+Y = function (g)
+      local a = function (f) return f(f) end
+      return a(function (f)
+                 return g(function (x)
+                             local c=f(f)
+                             return c(x)
+                           end)
+               end)
+end
+
+
+-- factorial without recursion
+F = function (f)
+      return function (n)
+               if n == 0 then return 1
+               else return n*f(n-1) end
+             end
+    end
+
+factorial = Y(F)   -- factorial is the fixed point of F
+
+-- now test it
+function test(x)
+	io.write(x,"! = ",factorial(x),"\n")
+end
+
+for n=0,16 do
+	test(n)
+end