4.27 Exercise 4.27
Let’s run through the given session in the lazy REPL to see an example of how mutation and lazy evaluation can interact with one another strangely. Suppose we begin with the following:
(define count 0) (define (id x) (set! count (+ count 1)) x)
Now we do the following:
(define w (id (id 10)))
One thing to note is that, when a definition is evaluated, the value being assigned is evaluated. So even before we’ve used the value w, the expression of its value has been evaluated. This means that one id, the outer one, has been evaluated, and count has been incremented once for it.
But what about the inner id expression? Remember that the argument to id is simply passed through – in other words, (id 10) would evaluated to 10. However, that expression has not been evaluated yet, because the value of w hasn’t been forced yet. Therefore, the value of count at this point is 1.
After we evaluated w (which results in 10, as we should have expected), count is 2. Since the value of w was memoized, every new evaluation of w will result in no change to count.