[previous] [up] [next]     [index]
Next: Sequencing Expression Evaluations Up: Assignment to Variables Previous: Assignment to Variables

Simple Assignments at Work

Consider the following definition and expression:

(define x 3)

(local ((define z (set! x (+ x 2)))) x)

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.

The first step in the evaluation lifts the local definition:

(define x 3)

(define z (set! x (+ x 2)))

x

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 x 3)

(define z (set! x 5))

x

That value is 5 because the current value of x is 3.

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)

(define z (void))

x

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.

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.


Exercises

Exercise 35.1.1

Consider the following:

  1. (set! x 5)
    
  2. (define x 3)
    (set! (+ x 1) 5) 
    
  3. (define x 3)
    (define y 7) 
    (define z false)
    

    (set! (if z x y) 5)

Which ones are syntactically legal programs? Which ones are illegal? Solution

Exercise 35.1.2

Evaluate the following program:

(define x 1)
(define y 1)

(local ((define u (set! x (+ x 1))) (define v (set! y (- y 1)))) (* x y))

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
(define x 1)
(define y 1)

(local ((define u ...) (define v ...)) (* x y))

where the right-hand sides of the definitions have been removed. What would this expression have produced before the introduction of set!-expressions? Solution


[previous] [up] [next]     [index]
Next: Sequencing Expression Evaluations Up: Assignment to Variables Previous: Assignment to Variables

PLT