# Scheme-modifying vector of vectors

I am a beginner programist. I have to write a simple program in pure Scheme that will print out a rectangle of given height and width (for example 4,6):

111111 100001 100001 111111

1 is a black border, 0 is an empty space.

I am encountering an obstacle. My solution is a vector of vectors #(#(111111) (100001) (100001) (100001)) because it is easy to modify later. First I create vector of vectors filled with zeros and later I want to set its values to 1.

The problem is that for example if I want to change the first element of first vector to 1 I dont know why the program sets first elements of ALL vectors to 1. So I want to get: : #(100000) (000000) (000000) (000000)) but i get #(#(100000) (100000) (100000) (100000))

The code is:

(vector-set! (vector-ref vect 0) 0 "1")

Does anyone have an explenation on maybe an easier solution ?

## Answers

This will avoid the aliasing problem:

(define (make-board n) (let ((table (make-vector n))) (let filling ((i 0)) (if (= i n) table (begin (vector-set! table i (make-vector n 0)) (filling (+ i 1)))))))

Wild guess, you've constructed the 2-d vector like so:

(define row #(0 0 0 0 0 0)) (define table (vector row row row row))

Then what you have is a vector, called table, that holds four *references* to row, while what you need is four *copies* of row that can be independently modified. You can get that with

(define table (vector (vector-copy row) (vector-copy row) (vector-copy row) (vector-copy row)))

(In technical terms, your vectors are *sharing structure*. Often, this is a good thing, but when you're using destructive modification, e.g. vector-set!, it may lead to surprising results.)