SICP Exercise 3.57 fibs using add-streams

Exercise 3.57.  How many additions are performed when we compute the nth Fibonacci number using the definition of fibs based on the add-streams procedure? Show that the number of additions would be exponentially greater if we had implemented (delay <exp>) simply as (lambda () <exp>), without using the optimization provided by the memo-proc procedure described in section 3.5.1.64

SOLUTION

The Racket code and explanation is here.

The Scheme code and tests are here.

EXPLANATION

(define fibs
(stream-cons
0
(stream-cons
1
(add-streams (stream-rest fibs) fibs)
)
)
)

Number of additions performed:

0th Fibonacci number (0): 0 additions
1st Fibonacci number (1): 0 additions
2nd Fibonacci number (1): 1 addition
3rd Fibonacci number (2): 2 additions
4th Fibonacci number (3): 3 additions

As we can see above, for every higher Fibonacci number, one additional addition is performed. So when we compute the nth Fibonacci number, n - 1 additions are performed in total.

Now, if we had implemented (delay <exp>) simply as (lambda () <exp>) without memoization, then, upon accessing the nth Fibonacci number using (stream-ref fibs n) where n > 1, add-streams is executed which accesses the fibs stream twice. Since accessing fibs results in a call to add-streams, the result is that every add-streams call results in two calls to add-streams. This pattern results in 2^n additions. 

Therefore the number of additions will be exponentially greater compared to when we use memoization in the 'delay' implementation.

Comments

Popular posts from this blog

SICP Exercise 2.56 differentiation rule

SICP Exercise 1.28 (Miller-Rabin Test)

SICP Exercise 4.18 a alternative strategy for interpreting internal definitions