Search code examples
refactoringiterationlispracketsicp

SICP - Code improvement with more abstraction


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?


Solution

  • 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.