chicken-users
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Chicken-users] Set! question


From: Graham Fawcett
Subject: Re: [Chicken-users] Set! question
Date: Fri, 4 May 2007 09:10:03 -0400

On 5/4/07, William Ramsay <address@hidden> wrote:
I'm suddenly confused on how set! works.     Suppose I have two
variables, A & B.    If A ="Hello"
and I call (set! B A), both A and B will equal "Hello".   If I call
(set! B "Good-bye") I would assume
that B now equals "Good-bye" and that A still equals "Hello", but is
this the case?

Right.

My real call was a bit more complex (i.e (set! B (vector-ref A 6))).
In this case I assume the same
will be true.   If (vector-ref A 6) equals "Hello" as above, when I set
B to "Good-bye" the vector
reference also changes.

Wrong:

#;1> (define A (vector "hola" "guten tag" "hello"))
#;2> A
#("hola" "guten tag" "hello")
#;3> (define B #f)
#;4> (set! B (vector-ref A 2))
#;5> B
"hello"
#;6> (vector-set! A 2 "foo")
#;7> A
#("hola" "guten tag" "foo")
#;8> B       ; changing A doesn't change B
"hello"
#;9> (set! B "bye")
#;10> A     ; changing B doesn't change A
#("hola" "guten tag" "foo")
#;11> B
"bye"

At first A[2] and B point to the same object, a string containing the
characters "hello". In C, the analogy would be two (char *) variables
pointing to the same memory location. Calling (set! B other) sets the
(char *) B to point to the address of the object "other", so to speak.

Consider this:

#;13> (set! B (vector-ref A 0))
#;14> B
"hola"
#;15> (string-set! B 0 #\H) ; modify the string!
#;16> B
"Hola"
#;17> A
#("Hola" "guten tag" "foo")

In this case, B and A[0] both refer to the same string, containing the
characters "hola". We change the first character in that string, and
the change is reflected in "both places" (because, of course, "both
places" are the same place).

Does that help?
Graham




reply via email to

[Prev in Thread] Current Thread [Next in Thread]