An assignment can also occur in a function body:
(define x 3)Here the function swap-x-y consumes two values and performs two set!s.(define y 5)
(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))
(swap-x-y x y)
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)From here we proceed with the usual substitution rule for application:(define y 5)
(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))
(swap-x-y 3 5)
(define x 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.(define y 5)
(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))
(begin (set! x 5) (set! y 3))
The next two steps are also the last ones and thus they accomplish what the name of the function suggests:
(define x 5)The value of the application is invisible because the last expression evaluated was a set!-expression.(define y 3)
(define (swap-x-y x0 y0) (begin (set! x y0) (set! y x0)))
(void)
In summary, functions with set! have results and effects. The result may be invisible.
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)What is the result? What is increase-x's effect? Solution(define (increase-x) (begin (set! x (+ x 1)) x))
(increase-x) (increase-x) (increase-x)
Exercise 35.3.3
Evaluate the following program by hand:
(define x 0)What is the result? What is switch-x's effect? Solution(define (switch-x) (begin (set! x (- x 1)) x))
(switch-x) (switch-x) (switch-x)
Exercise 35.3.4
Evaluate the following program by hand:
(define x 0)What is the effect of change-to-3? What is its result? Solution(define y 1)
(define (change-to-3 z) (begin (set! y 3) z))
(change-to-3 x)