Subject: Re: pls explain set! scoping
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 1996/10/22
Newsgroups: comp.lang.scheme
Message-ID: <54hgaj$gif@tokyo.engr.sgi.com>

Sean Case <gscase@tpgi.com.au> wrote:
+---------------
| There is no way in Scheme, as far as I know, to pass a variable,
| rather than a value, as an argument _to a function_.
+---------------

Well, what you *can* do is pass a *procedure* as a parameter. This can
give you a kind of object-oriented metaphor. For example, let's make a
"class" of settable/fetchable objects, then instantiate one of them, and
then change it:

	> (define make-mutable-thing
	    (lambda (initial-value)
	      (let ((hidden-thing initial-value))
	        (lambda (op . arg)
	          (case op
		    ((fetch) hidden-thing)
		    ((set!) (set! hidden-thing (car arg)))
		    (else
		      (error "wrong operation on mutable-thing:" op arg)))))))
Then:

	> (define foo (make-mutable-thing 47))
	> (foo 'fetch)
	47
	> (foo 'set! 53)
	> (foo 'fetch)
	53
	> (foo 'bletch 34 53)
	wrong operation on mutable-thing: bletch (34 53)
	>

And such "objects" (procedures) can then be passed (by "value") to other
procedures that invoke the getting & setting operations deep inside them:

	> (foo 'fetch)
	53
	> (define mutable-thing-incrementor!
	    (lambda (x)
	      (let ((old (x 'fetch)))
	        (x 'set! (+ old 1)))))
	> (mutable-thing-incrementor! foo)
	> (mutable-thing-incrementor! foo)
	> (foo 'fetch)
	55
	> 

Note that two instances of a "mutable-thing" are distinct:

	> (define a (make-mutable-thing 5))
	> (define b (make-mutable-thing 17))
	> (a 'fetch)
	5
	> (b 'fetch)
	17
	> (mutable-thing-incrementor! b)
	> (b 'fetch)
	18
	> (a 'fetch)
	5
	> 

The reason I call this sort of a "class" is that you can put more hidden
variables in the top-level "let" and more branches in the "case" and get
much more complicated "objects" and behavior. See any Scheme text for more...


-Rob

p.s.
Some Schemes also provide explicit "boxed variables", which are kind
of like a pair with no cdr, and special operations "unbox" and "set-box!"
analogous to "car" and "set-car!" on pairs.

-----
Rob Warnock, 7L-551		rpw3@sgi.com
Silicon Graphics, Inc.		http://reality.sgi.com/rpw3/
2011 N. Shoreline Blvd.		Phone: 415-933-1673  FAX: 415-933-0979
Mountain View, CA  94043	PP-ASEL-IA