Chapter 1, Building Abstractions with Procedures

Section - Procedures and the Processes They Generate

Exercise 1.11


Procedure for Recursive Process:

1
2
3
4
5
6
7
8
9
10
(define (f n)
    (if (> n 3)
        n
        (+ 
            (f (- n 1)) 
            (f (- n 2)) 
            (f (- n 3))
        )        
    )
)        

Procedure for Iterative Process:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
(define (f-new n)
  (define (comp t3 t2 t1)
    (+
       t3
       (* 2 t2)
       (* 3 t1)
    )
  )  

  (define (f-itr f3 f2 f1 c)
    (if (= c 2)
      f3
      (f-itr
             (comp f3 f2 f1)
             f3
             f2
             (dec c)             
      )
    )
  )

  (if (< n 3)
       n
       (f-itr
             (f-new 2)
             (f-new 1)
             (f-new 0)             
             n)
   )
)