[racket] how can I change only one element in the vector?

81 views
Skip to first unread message

김태윤

unread,
Nov 20, 2010, 2:45:50 AM11/20/10
to users
hello
from the following code, I expected
'#(#(#("2" "2" "3") #("1" "2" "3")) #(#("1" "2" "3") #("1" "2" "3")))
but 
the interpreter pop the 
'#(#(#("2" "2" "3") #("2" "2" "3")) #(#("2" "2" "3") #("2" "2" "3")))
how can I change only one element in the vector?
===following code===
#lang racket
(define v (make-vector 2 
                       (make-vector 2 
                                    (vector "1" "2" "3"))))

(vector-set! (vector-ref (vector-ref v 0) 0) 0  "2")
v

Neil Van Dyke

unread,
Nov 20, 2010, 3:09:34 AM11/20/10
to 김태윤, users
"make-vector" is creating a new vector populated with *references* to a
single #("1" "2" "3") vector, *not* *copies* of the #("1" "2" "3") vector.

Since you've created one #("1" "2" "3") vector, changing it through one
reference changes all references to it.

(Aside to PLT people: This might be an example of having the default
writer show sharing could actually be helpful to beginners.)

--
http://www.neilvandyke.org/
_________________________________________________
For list-related administrative tasks:
http://lists.racket-lang.org/listinfo/users

김태윤

unread,
Nov 20, 2010, 3:31:27 AM11/20/10
to Neil Van Dyke, users
thank you !
could you tell me how to make new vector that does not refer to a single vector?

김태윤

unread,
Nov 20, 2010, 3:42:41 AM11/20/10
to Neil Van Dyke, users
is this code right way to do it?
#lang racket
(define v (build-vector 2 (λ (n) 
                            (build-vector 2 (λ (n) 
                                              (vector "1" "2" "3"))))))
  
  (vector-set! (vector-ref (vector-ref v 0) 0) 0  "2")
  v

Neil Van Dyke

unread,
Nov 20, 2010, 3:44:20 AM11/20/10
to 김태윤, users
김태윤 wrote at 11/20/2010 03:31 AM:
> thank you !
> could you tell me how to make new vector that does not refer to a
> single vector?

"make-vector" is not the correct way, but there are many other ways.

This will make the nested vectors like you originally intended:

(vector (vector (vector 1 2 3)
(vector 1 2 3))
(vector (vector 1 2 3)
(vector 1 2 3)))

You can also use procedures:

(define (make-xyz) (vector (make-yz) (make-yz)))
(define (make-yz) (vector (make-z) (make-z)))
(define (make-z) (vector 1 2 3))
(make-xyz)

Or, if you want to represent multiple dimensions, and you know the size
of each dimension, you can use a single vector and then do arithmetic of
the X, Y, Z to find the right index:

(vector 1 2 3 1 2 3 1 2 3 1 2 3)

Reply all
Reply to author
Forward
0 new messages