Consider the following definition and expression:
(define x 3)The definition says that x stands for 3. The local-expression introduces a definition for z. Its body is x so, in the past, the value of this local-expression would have been 3 (if anything). Now, with set! in the language, this is no longer true. To understand what happens, we must rewrite the program step by step until we have a final answer.(local ((define z (set! x (+ x 2)))) x)
The first step in the evaluation lifts the local definition:
(define x 3)Next we must determine the value of (set! x (+ x 2)). According to the general explanation of set!, this requires the evaluation of the right-hand side of the assignment:(define z (set! x (+ x 2)))
x
(define x 3)That value is 5 because the current value of x is 3.(define z (set! x 5))
x
Finally, the general explanation says that the effect of the set! expression is to change the value that the left-hand side variable represents. In our example this means that from now on, x is no longer 3 but 5. The best way to express this change is to modify the definition of x for the next step:
(define x 5)The value of set! is (void), the invisible value. By replacing the set!-expression with the invisible value, we indicate that its evaluation is finished.(define z (void))
x
At this point, it is easy to see that the result is 5. The first definition says that x currently represents 5, and the last expression is x. Hence the value of the function evaluation is 5.
Exercise 35.1.1
(set! x 5)
(define x 3) (set! (+ x 1) 5)
(define x 3) (define y 7) (define z false)(set! (if z x y) 5)
Exercise 35.1.2
Evaluate the following program:
(define x 1) (define y 1)If set! were not a part of the language, what could we say about the result of the local-expression? That is, consider the skeleton(local ((define u (set! x (+ x 1))) (define v (set! y (- y 1)))) (* x y))
(define x 1) (define y 1)where the right-hand sides of the definitions have been removed. What would this expression have produced before the introduction of set!-expressions? Solution(local ((define u ...) (define v ...)) (* x y))