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

Assignments and Functions

An assignment can also occur in a function body:

(define x 3)

(define y 5)

(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))

(swap-x-y x y)

Here the function swap-x-y consumes two values and performs two set!s.

Let us see how the evaluation works. Because (swap-x-y x y) is a function application, we need to evaluate the arguments, which are plain variables here. So we replace the variables with their (current) values:

(define x 3)

(define y 5)

(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))

(swap-x-y 3 5)

From here we proceed with the usual substitution rule for application:
(define x 3)

(define y 5)

(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))

(begin (set! x 5) (set! y 3))

That is, the application is now replaced by an assignment of x to the current value of y and of y to the current value of x.

The next two steps are also the last ones and thus they accomplish what the name of the function suggests:

(define x 5)

(define y 3)

(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))

(void)

The value of the application is invisible because the last expression evaluated was a set!-expression.

In summary, functions with set! have results and effects. The result may be invisible.


Exercises

Exercise 35.3.1

Consider the following function definition:

(define (f x y)
  (begin 
    (set! x y) 
    y)) 
Is it syntactically legal or illegal? Solution

Exercise 35.3.2

Evaluate the following program by hand:

(define x 3)

(define (increase-x) (begin (set! x (+ x 1)) x))

(increase-x) (increase-x) (increase-x)

What is the result? What is increase-x's effect? Solution

Exercise 35.3.3

Evaluate the following program by hand:

(define x 0)

(define (switch-x) (begin (set! x (- x 1)) x))

(switch-x) (switch-x) (switch-x)

What is the result? What is switch-x's effect? Solution

Exercise 35.3.4

Evaluate the following program by hand:

(define x 0)

(define y 1)

(define (change-to-3 z) (begin (set! y 3) z))

(change-to-3 x)

What is the effect of change-to-3? What is its result? Solution


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

PLT