2

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?

Barmar
  • 741,623
  • 53
  • 500
  • 612
TomatoFarmer
  • 463
  • 3
  • 13
  • The answers to this question might help: [_How are these nested vectors connected?_](https://stackoverflow.com/questions/56824929/how-are-these-nested-vectors-connected) – Alex Knauth Aug 30 '20 at 04:46

1 Answers1

3

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)))
Barmar
  • 741,623
  • 53
  • 500
  • 612