schemeracketr5rs

How are these nested vectors connected?


I've written a piece of code, which creates a vector 'scoreboard' that contains 3 seperate vectors of size 3, all containing the symbol ? at all indices 0-2. When i now execute a 'vector-set!' on the first vector of scoreboard, to change its first element to a 'X, vectors 2 and 3 will change too. How does this occur?

(define scoreboard (make-vector 3 (make-vector 3 '?)))
(define (display-scoreboard)
(display (vector-ref scoreboard 0))
(newline)
(display (vector-ref scoreboard 1))
(newline)
(display (vector-ref scoreboard 2))
(newline))

(define (X! pos)
(cond
((>= 3 pos) (vector-set! (vector-ref scoreboard 0) (- pos 1) 'X))
))

(display-scoreboard)
(X! 1)
(newline)
(display-scoreboard)

output:

#(? ? ?)
#(? ? ?)
#(? ? ?)

#(X ? ?)
#(X ? ?)
#(X ? ?)

Desired output:

#(? ? ?)
#(? ? ?)
#(? ? ?)

#(X ? ?)
#(? ? ?)
#(? ? ?)

Solution

  • enter image description here

    The image shows that (make-vector 3 (make-vector 3 '())) creates a vector that has the same row (vector) in all three slots.

    Instead, write (vector (vector '() '() '()) (vector '() '() '()) (vector '() '() '())). Or make a little helper function:

    (define (make-row) (vector '() '() '()))
    (vector (make-row) (make-row) (make-row))