fork(2) download
  1. -- Recursive Style
  2. f = function(a, b)
  3. if a == 0 then
  4. return b + 1
  5. elseif b == 0 then
  6. return f(a - 1, 1)
  7. else
  8. return f(a - 1, f(a, b - 1))
  9. end
  10. end
  11.  
  12. -- Continuation Passing Style
  13. g = function(a, b, c)
  14. if a == 0 then
  15. return c(b + 1)
  16. elseif b == 0 then
  17. return g(a - 1, 1, c)
  18. else
  19. return g(a, b - 1, function(x)
  20. return g(a - 1, x, c)
  21. end)
  22. end
  23. end
  24.  
  25. -- Loop Style
  26. h = function(a, b)
  27. local s = {}
  28. while true do
  29. if a == 0 then
  30. if #s ~= 0 then
  31. s[#s](b + 1)
  32. table.remove(s)
  33. else
  34. break
  35. end
  36. elseif b == 0 then
  37. a = a - 1
  38. b = 1
  39. else
  40. b = b - 1
  41. table.insert(s, (function(a_)
  42. return function(x)
  43. a = a_ - 1
  44. b = x
  45. end
  46. end)(a))
  47. end
  48. end
  49. return b + 1
  50. end
  51.  
  52. print(f(3, 3))
  53.  
  54. print(g(3, 3, function(x)
  55. return x
  56. end))
  57.  
  58. print(h(3, 3))
  59.  
Success #stdin #stdout 0s 2788KB
stdin
Standard input is empty
stdout
61
61
61