[plt-scheme] Question about variable scope in lists

From: Zhu Chongkai (mathematica at citiz.net)
Date: Sat Feb 26 03:34:31 EST 2005

  
======= At 2005-02-26, 16:13:30 A00453721 wrote: =======

>Thanks for the help! Now this is getting even more confusing for me :P
>
>I found a post made by another user of the list stating a similar 
>problem with an even simpler code:
>
>--------------------------------------------------------------------------------
>
>
>
>John, look at this mod of your code:
>
>(define mylist '(hi-there))
>
>(define (changemylist x)
> (begin
>   (set! x '(yall))
>   x))
>
>(define myvector #(hi-there))
>
>(define changemyvector
> (lambda (x)
>   (vector-set! x 0 'yall)
>   x))
>
>mylist
>(changemylist mylist)
>mylist
>
>myvector
>(changemyvector myvector)
>myvector
>
>(define mylist '(whatcha-doin?))
>mylist
>(set! mylist '(nuthin))
>mylist
>
>
>
>Welcome to DrScheme, version 203.
>Language: Pretty Big (includes MrEd and Advanced) custom.
>
>(hi-there)
>(yall)
>(hi-there)      <-------------- Here's where it all gets confusing!
>#1(hi-there)
>#1(yall)
>#1(yall)
>(whatcha-doin?)
>(nuthin)
>>/ 
>/
>The 3rd `whatcha-doin?/nuthin' exchange shouldn't surprise you.
>
>What's suprising is the first one, that `changemylist' didn't change
>`mylist'!  If you a standard Scheme source, e.g.  R5RS or SICP, you'll
>see that the usual explanation of this is in terms of environments:
>that `changemylist' defines an environment and binds `x' to a
>location, and stores first `hi-there' in this location, and then
>stores `yall' in this location. but `changemylist' does nothing to the
>global value of `mylist'.  Pretty mind-boggling stuff, and HtDP offers
>a simplified semantics.
>
>--------------------------------------------------------------------------------
>
>Now, bearing in mind that the procedure changemylist did not changed the
>
>global variable mylist, is
>there any way to do such value assignment inside a function?
>
>Thanks again.
>
= = = = = = = = = = = = = = = = = = = =
			
The easiest way is to use 'box'es instead of directly putting a value 
in a global variable. 


3.10  Boxes

MzScheme provides boxes, which are records that have a single field: 

* (box v) returns a new mutable box that contains v.

* (unbox box) returns the content of box. For any v, (unbox (box v)) returns v.

* (set-box! mutable-box v) sets the content of mutable-box to v.

* (box? v) returns #t if v is a box, #f otherwise.

Two boxes are equal? if the contents of the boxes are equal?.

Posted on the users mailing list.