Advertisement
timothy235

sicp-1-2-1-linear-recursion-and-iteration

Feb 15th, 2016
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Racket 1.68 KB | None | 0 0
  1. #lang racket
  2.  
  3. ;; 1.9
  4.  
  5. (define (inc x) (add1 x))
  6. (define (dec x) (sub1 x))
  7.  
  8. ;; plus is recursive but not tail recursive hence not iterative
  9.  
  10. (define (plus a b)
  11.   (if (zero? a)
  12.       b
  13.       (inc (plus (dec a) b))))
  14.  
  15. ;; (plus 4 5)
  16. ;; (inc (plus 3 5))
  17. ;; (inc (inc (plus 2 5)))
  18. ;; (inc (inc (inc (plus 1 5))))
  19. ;; (inc (inc (inc (inc (plus 0 5)))))
  20. ;; (inc (inc (inc (inc 5))))
  21. ;; (inc (inc (inc 6)))
  22. ;; (inc (inc 7))
  23. ;; (inc 8)
  24. ;; 9
  25.  
  26. ;; new-plus is tail recursive hence iterative
  27.  
  28. (define (new-plus a b)
  29.   (if (zero? a)
  30.       b
  31.       (new-plus (dec a) (inc b))))
  32.  
  33. ;; (new-plus 4 5)
  34. ;; (new-plus 3 6)
  35. ;; (new-plus 2 7)
  36. ;; (new-plus 1 8)
  37. ;; (new-plus 0 9)
  38. ;; 9
  39.  
  40. ;; 1.10
  41.  
  42. ;; Ackermann function a very fast-growing recursive function
  43.  
  44. (define (A x y)
  45.   (cond [(zero? y) 0]
  46.         [(zero? x) (* 2 y)]
  47.         [(= y 1) 2]
  48.         [else (A (sub1 x)
  49.                  (A x (sub1 y)))]))
  50.  
  51. (A 1 10)
  52. ;; 1024
  53. (A 2 4)
  54. ;; 65536
  55. (A 3 3)
  56. ;; 65536
  57.  
  58. (define (f n) (A 0 n))
  59. ;; f(n) = 2 * n by definition
  60.  
  61. (f 0)
  62. ;; 0
  63. (f 1)
  64. ;; 2
  65. (f 2)
  66. ;; 4
  67.  
  68. (define (g n) (A 1 n))
  69. ;; g(n) = 2 ^ n for n > 0 because
  70. ;; g(1) = A(1, 1) = 2 by definition and
  71. ;; g(n) = A(1, n)
  72.      ;; = A(0, A(1, n - 1))
  73.      ;; = f(A(1, n - 1))
  74.      ;; = 2 * A(1, n - 1)
  75.      ;; = 2 * g(n - 1)
  76.  
  77. (g 0)
  78. ;; 0
  79. (g 1)
  80. ;; 2
  81. (g 2)
  82. ;; 4
  83. (g 3)
  84. ;; 8
  85. (g 4)
  86. ;; 16
  87. (g 5)
  88. ;; 32
  89.  
  90. (define (h n) (A 2 n))
  91. ;; h(n) = an exponentiation tower of n 2's for n > 0 because
  92. ;; h(1) = A(2, 1) = 2 by definition and
  93. ;; h(n) = A(2, n)
  94.      ;; = A(1, A(2, n - 1))
  95.      ;; = g(A(2, n - 1))
  96.      ;; = 2 ^ A(2, n - 1)
  97.      ;; = 2 ^ h(n - 1)
  98.  
  99. (h 0)
  100. ;; 0
  101. (h 1)
  102. ;; 2
  103. (h 2)
  104. ;; 4
  105. (h 3)
  106. ;; 16
  107. (h 4)
  108. ;; 65536 ; 2 ^ 16
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement