[plt-scheme] nested vectors

From: Chongkai Zhu (czhu at cs.utah.edu)
Date: Sat Feb 14 16:40:12 EST 2009

This is what (make-vector n fill) does: it create a vector of length n, 
and every slot of the vector is filled with `fill'. In your case, the 
outside `make-vector' created a vector of length 17. It will not copy 
the inner (make-vector 17) 17 times. Instead, all 17 slots of the outer 
vector refers to the same area (in memory). To be more clear:

(define a (make-vector 16))
(define b (make-vector 17 a))
(vector-set! a 2 1)

Now a is #(0 1), while b is #(a a) thus #(#(0 1) #(0 1) #(0 1)), the 
same as you saw in your example.

I guess your want to create a two dimension array. To do that in Scheme, 
you need:

(define (make-array n)
  (let ((a (make-vector n)))
    (let loop ((i 0))
      (when (< i n)
        (vector-set! a i (make-vector n))
        (loop (add1 i))))
    a))

In which the loop actually allocate space for all sub-vector.

Chongkai

wooks wrote:
> working in Pretty Big
>
> (define deposits (make-vector 17 (make-vector 17)))
>
> Now I want to set the value of the index entry [0,11] in deposits to
> 39.
>
> (vector-set! (vector-ref deposits 0) 11 39) gives a weird result.
> Please explain the result and correct me.
>
> #(#(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0)
>   #(0 0 0 0 0 0 0 0 0 0 0 39 0 0 0 0 0))
> _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>   



Posted on the users mailing list.