Recall from intermezzo
that vectors, like structures,
are compound values. To extract a value from a structure, programs use
selector operations. To extract a value from a vector, programs use natural
numbers as indices. Hence functions that process vectors defer to
auxiliary functions that process vectors and natural numbers.
Not surprisingly, vectors, like structures, are mutable compound values. The only mutator for vectors is vector-set!, a function that consumes a vector, an index, and a value. Thus, for example, the following program evaluates to 'blank:
(define X (vector 'a 'b 'c 'd))The four vector-set! expressions change X so that all of its four fields contain 'blank. The last expression extracts the value of one of the fields.(begin (vector-set! X 0 'blank) (vector-set! X 1 'blank) (vector-set! X 2 'blank) (vector-set! X 3 'blank) (vector-ref X 2))
In general, an evaluation concerning mutable vectors proceeds just like an evaluation for mutable structures. In particular, a vector expression introduces a new definition:
(list (vector 1 2 3)) = (list v) ;; add to top-level definitions: (define v (vector 1 2 3))The variable name v is new and unique. Similarly, a vector-set! expression modifies a part of a vector definition:
(set-vector! (vector 1 2 3) 0 'a)Finally, effects to vectors are shared just like effects to structures.= (define v (vector 1 2 3)) (set-vector! v 0 'a)
= (define v (vector 'a 2 3)) (void)
Exercise 40.4.1
Evaluate the following program:
(define X (vector 0 0 0 0))Show all steps. Solution(define Y X)
(begin (vector-set! X 0 2) (vector-set! Y 1 (+ (vector-ref Y 0) (vector-ref Y 1))) (vector-ref Y 1))
Exercise 40.4.2
Develop the function clear, which consumes a vector with three slots and sets them to 0. Solution
Exercise 40.4.3
Develop the function swap, which consumes a vector with two slots and swaps the values in these slots. Solution
Exercise 40.4.4
Extend the board representation of exercise
with the
function
;; board-flip! : board N N -> boolean ;; to negate the board position with indices i, j on a-board (define (board-set! a-board i j) ...)Don't forget to develop examples and tests for the function. Solution