[plt-scheme] Question about variable scope in lists

From: A00453721 at itesm.mx (A00453721 at itesm.mx)
Date: Sat Feb 26 00:33:05 EST 2005

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:


Similarly, I studied a predicate removal function from GUILE Scheme, defined
like this:

(define (delete-if! pred l)
  "Destructive version of `remove-if'."
  (let delete-if ((l l))
    (cond ((null? l) '())
      ((pred (car l)) (delete-if (cdr l)))
       (set-cdr! l (delete-if (cdr l)))

And again, when I tested it in the interactions window like this...

( define R '( #f #t #t #f #f #t ) )
( delete-if! not R )

The output was:

(#t #t #t)

but when I reevaluated R, I got:

(#f #t #t #t)

Aren't these destructive functions supposed to have modified the contents
of both U and R?

Or is there anything I'm getting wrong about variable scopes? I ask this
mainly because I'm having problems with an "in-place" sorting algorithm I
was asked to develop. I would appreciate any kind of help.


Posted on the users mailing list.