[previous] [up] [next]     [index]
Next: Changing VariablesChanging Structures Up: Mutable Structures Previous: Mutable Structures

Mutable Vectors

Recall from intermezzo [cross-reference] 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))

(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))

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.

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)

= (define v (vector 1 2 3)) (set-vector! v 0 'a)

= (define v (vector 'a 2 3)) (void)

Finally, effects to vectors are shared just like effects to structures.


Exercises

Exercise 40.4.1

Evaluate the following program:

(define X (vector 0 0 0 0))

(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))

Show all steps. Solution

Exercise 40.4.2

Develop the function clear, which consumes a vector with three slots and sets them to 0Solution

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 [cross-reference] 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


[previous] [up] [next]     [index]
Next: Changing VariablesChanging Structures Up: Mutable Structures Previous: Mutable Structures

PLT