No idea how to solve SICP exercise 1.11

Posted by Javier Badia on Stack Overflow See other posts from Stack Overflow or by Javier Badia
Published on 2010-03-02T19:18:17Z Indexed on 2014/06/08 21:25 UTC
Read the original article Hit count: 223

Filed under:
|

This is not homework.

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.

Implementing it recursively is simple enough. But I couldn't figure out how to do it iteratively. I tried comparing with the Fibonacci example given, but I didn't know how to use it as an analogy. So I gave up (shame on me) and Googled for an explanation, and I found this:

(define (f n)
   (if (< n 3)
       n
       (f-iter 2 1 0 n)))

(define (f-iter a b c count)
   (if (< count 3)
       a
       (f-iter (+ a (* 2 b) (* 3 c))
               a
               b
               (- count 1))))

After reading it, I understand the code and how it works. But what I don't understand is the process needed to get from the recursive defintion of the function to this. I don't get how the code formed in someone's head.

Could you explain the thought process needed to arrive at the solution?

© Stack Overflow or respective owner

Related posts about Scheme

Related posts about sicp