<< Previous exercise (3.26)
| Index |
Next exercise (3.28) >>
The (memo-fib) never computes the same result twice. the call tree is a linear list.
If define memo-fib to be (memorize fib), the procedure won't work. because fib calls itself to compute (fib n) before applies memorize.
(define memo-fib (memoize fib))
willl not work because when evaluating code for (memoize fib); (fib x) will be evaluated whose enclosing envrionment is the global environment and thus memoization is lost.
Instead of recoding fib into memo-fib as shown in SICP (which seems like a very error-prone way of adding memoize to an existing function). The following works in DrRacket using #lang racket
(set! fib (memoize fib))
It sets fib in the global environment to (memoize fib) which also causes the recursive calls within fib to call the redefined version.
This will not work under the environment model for evaluation as described in the book. This is because f in memoize will be bound to procedure object that was created via lambda expression for fib; and this procedure object still has global envrionment as the enclosing environment.
(note, all procedures can be created only via lambda expressions).