0

I am using the SICP book and I did this exercise:

1.11 A function f is defined by the rule that f(n) = n if n<3 and f(n) = f(n - 1) + 2f(n - 2) + 3f(n - 3) if n> 3. Write a procedure that computes f by means of a recursive process. Write a procedure that computes f by means of an iterative process.

The recursive process is easy. The iterative one is harder.

I did this code:

(define (f-ltail n)
  (f-iter 0 n))

(define (f-iter produto n)
  (define counter (- n 2))  
  (cond ((< n 3) n)
        ((= counter 0) produto)
        (else (+ produto (+ (f-iter produto (- n 1))
                            (* 2 (f-iter produto (- n 2)))
                            (* 3 (f-iter produto (- n 3))))))))

My professor keeps saying that we should avoid defining things that need not to be defined.

Is this definition really need?

(define counter (- n 2)) 

If not, how can I eliminate this piece of code?

mobiuseng
  • 2,326
  • 1
  • 16
  • 30
  • Why my post was downvoted? I am new to stack overflow, could not figure it out... –  Sep 05 '16 at 20:45
  • 1
    Since you are just using `counter` one place, to see that `(= (- n 2) 0)`, then it's just a difficult way to do `(= n 2)` Since the first term hits on everything less than `3` we know `n` cannot be `2` in the second term since it's `3` or higher. An iterative process would be tail recursive so all your calculations should be on the arguments. – Sylwester Sep 05 '16 at 22:05
  • Let's begin with the fact that `f-iter` does not generate iterative process: for that it must be in tail-call position. In fact, it should be linearly iterative process, but your procedure will result in tree recursion. Just go over Fibonacci example in SICP and correct your code the same way they did it. – mobiuseng Sep 06 '16 at 07:03
  • I think this one is much easier if you "recurse upwards". – molbdnilo Sep 06 '16 at 12:02

1 Answers1

0

The book gives an example where the Fibonacci sequence is computed iteratively.

(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))))

Note that instead of defining a counter variable inside the fib-iter function, a parameter is passed to the function to keep track of that value. You could follow the same pattern in your function.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880