diff options
author | Pavel Labath <pavelo@centrum.sk> | 2011-05-16 10:58:21 (GMT) |
---|---|---|
committer | Paul Tagliamonte <paultag@fluxbox.org> | 2012-04-07 02:08:41 (GMT) |
commit | 0fa62fe1598c5b04925c0b7b98d0d00d28d10d88 (patch) | |
tree | ccc2dd040a03b294b17abaa4da55ca00ed9b82a7 /libs/lua/test/factorial.lua | |
parent | 7b6dc2ad72a4c4ecd20eddbfb6f1b4c3bd2a7024 (diff) | |
download | fluxbox_paul-0fa62fe1598c5b04925c0b7b98d0d00d28d10d88.zip fluxbox_paul-0fa62fe1598c5b04925c0b7b98d0d00d28d10d88.tar.bz2 |
Add lua as an internal library in libs/lua
Diffstat (limited to 'libs/lua/test/factorial.lua')
-rw-r--r-- | libs/lua/test/factorial.lua | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/libs/lua/test/factorial.lua b/libs/lua/test/factorial.lua new file mode 100644 index 0000000..7c4cf0f --- /dev/null +++ b/libs/lua/test/factorial.lua | |||
@@ -0,0 +1,32 @@ | |||
1 | -- function closures are powerful | ||
2 | |||
3 | -- traditional fixed-point operator from functional programming | ||
4 | Y = function (g) | ||
5 | local a = function (f) return f(f) end | ||
6 | return a(function (f) | ||
7 | return g(function (x) | ||
8 | local c=f(f) | ||
9 | return c(x) | ||
10 | end) | ||
11 | end) | ||
12 | end | ||
13 | |||
14 | |||
15 | -- factorial without recursion | ||
16 | F = function (f) | ||
17 | return function (n) | ||
18 | if n == 0 then return 1 | ||
19 | else return n*f(n-1) end | ||
20 | end | ||
21 | end | ||
22 | |||
23 | factorial = Y(F) -- factorial is the fixed point of F | ||
24 | |||
25 | -- now test it | ||
26 | function test(x) | ||
27 | io.write(x,"! = ",factorial(x),"\n") | ||
28 | end | ||
29 | |||
30 | for n=0,16 do | ||
31 | test(n) | ||
32 | end | ||