why is one call to 'vector-set!' changing several vectors in a nested vector, when given one inner vector?

Viewed 57

running the block of code below

#lang racket
(define nested-vector (make-vector 2 (make-vector 2 'a)))

(define inner-vector (vector-ref nested-vector 0)) 
(vector-set! inner-vector 0 'b)
(displayln nested-vector)

it displays:

#(#(b a) #(b a))

what I would expect it to display is:

#(#(b a) #(a a))

meaning that only the inner-vector would change.

why does vector-set! behave like this?

1 Answers

Your code is equivalent to:

(define vector2 (make-vector 2 'a))
(define nested-vector (make-vector 2 vector2))

When written this way, you should be able to see that the inner vectors are both the same vector, not two different vectors. So when you modify it, both elements of nested-vector are affected.

To make a vector with two distinct nested vectors, you need to call make-vector separately for each element.

(define nested-vector (vector (make-vector 2 'a) (make-vector 2 'a)))
Related