[plt-scheme] Question about variable scope in lists
On Feb 26, 2005, at 12:33 AM, A00453721 at itesm.mx wrote:
> For list-related administrative tasks:
> http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> Greetings. First of all, I would like to clarify that, while I am a CS
> student,
> I'm not explicitly asking for help on my assignment. I would just like
> an
> explanation of why is this happening:
>
> Currently, I'm investigating the effects of destructive modifications
> on
> variables passed to procedures using Dr. Scheme.
>
> While reading the "Teach yourself Scheme in fixnum days" study book, I
> found
> this destructive code which reverses a list "in-place".
>
> (define reverse!
> (lambda (s)
> (let loop ((s s) (r '()))
> (if (null? s) r
> (let ((d (cdr s)))
> (set-cdr! s r)
> (loop d s))))))
>
> However, I tried it in the interactions windows like this:
>
> ( define U '( 1 2 3 4 5 6 7 8 ) )
> ( reverse! U )
>
> Not to my surprise, the output was:
>
> (8 7 6 5 4 3 2 1)
>
> but when I asked the interpreter to reevaluate U, it just displayed:
>
> (1)
It's nice to keep an understanding of the difference between changing a
binding and changing a value. The first one changes what value an
identifier is bound to, the second changes the value itself.
Nowhere in this program do you do a "(set! U ...)" or a second "(define
U ...)", so you're not changing the binding for U. U still refers to
the same value that it did at the beginning of the computation.
But wait! At the beginning, U was bound to `(1 2 3 4 5 6 7 8), and now
it's bound to `(1)... how can that be the "same value"? Well, in a
world with set-car! and set-cdr!, you have to realize that values can
change. So, U was bound to a cons pair whose first element was 1 and
whose second element was another value that represents `(2 3 4 5 6 7
8). After running the in-place reverse, you've done a set-cdr! on this
cons pair, so that its second element is now the null value.
Draw some pictures to convince yourself, if it's not already clear.
This would be a great use for Slideshow.
john
p.s.: if you want to see U refer to the new value, you could just do it
like this: (set! U (reverse! U))
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/pkcs7-signature
Size: 2169 bytes
Desc: not available
URL: <http://lists.racket-lang.org/users/archive/attachments/20050226/86b8d9a0/attachment.p7s>