PageRenderTime 20ms CodeModel.GetById 12ms app.highlight 4ms RepoModel.GetById 2ms app.codeStats 0ms

/External/lua-5.1.4/test/factorial.lua

http://awoe.googlecode.com/
Lua | 32 lines | 22 code | 6 blank | 4 comment | 4 complexity | 04c1782798e988b2882a19b77d02a6b6 MD5 | raw file
 1-- function closures are powerful
 2
 3-- traditional fixed-point operator from functional programming
 4Y = 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)
12end
13
14
15-- factorial without recursion
16F = 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
23factorial = Y(F)   -- factorial is the fixed point of F
24
25-- now test it
26function test(x)
27	io.write(x,"! = ",factorial(x),"\n")
28end
29
30for n=0,16 do
31	test(n)
32end