2
0

factorial.lua 707 B

1234567891011121314151617181920212223242526272829303132
  1. -- function closures are powerful
  2. -- traditional fixed-point operator from functional programming
  3. Y = function (g)
  4. local a = function (f) return f(f) end
  5. return a(function (f)
  6. return g(function (x)
  7. local c=f(f)
  8. return c(x)
  9. end)
  10. end)
  11. end
  12. -- factorial without recursion
  13. F = function (f)
  14. return function (n)
  15. if n == 0 then return 1
  16. else return n*f(n-1) end
  17. end
  18. end
  19. factorial = Y(F) -- factorial is the fixed point of F
  20. -- now test it
  21. function test(x)
  22. io.write(x,"! = ",factorial(x),"\n")
  23. end
  24. for n=0,16 do
  25. test(n)
  26. end