The exercise tells you to write two functions, one that computes f
"by means of a recursive process", and another that computes f
"by means of an iterative process". You did the recursive one. Since this function is very similar to the fib
function given in the examples of the section you linked to, you should be able to figure this out by looking at the recursive and iterative examples of the fib
function:
; Recursive
(define (fib n)
(cond ((= n 0) 0)
((= n 1) 1)
(else (+ (fib (- n 1))
(fib (- n 2))))))
; Iterative
(define (fib n)
(fib-iter 1 0 n))
(define (fib-iter a b count)
(if (= count 0)
b
(fib-iter (+ a b) a (- count 1))))
In this case you would define an f-iter
function which would take a
, b
, and c
arguments as well as a count
argument.
Here is the f-iter
function. Notice the similarity to fib-iter
:
(define (f-iter a b c count)
(if (= count 0)
c
(f-iter (+ a (* 2 b) (* 3 c)) a b (- count 1))))
And through a little trial and error, I found that a
, b
, and c
should be initialized to 2
, 1
, and 0
respectively, which also follows the pattern of the fib
function initializing a
and b
to 1
and 0
. So f
looks like this:
(define (f n)
(f-iter 2 1 0 n))
Note: f-iter
is still a recursive function but because of the way Scheme works, it runs as an iterative process and runs in O(n)
time and O(1)
space, unlike your code which is not only a recursive function but a recursive process. I believe this is what the author of Exercise 1.1 was looking for.