Subject: Re: pls explain set! scoping
From: (Rob Warnock)
Date: 1996/10/22
Newsgroups: comp.lang.scheme
Message-ID: <54hgaj$>

Sean Case <> 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)))
		      (error "wrong operation on mutable-thing:" op arg)))))))

	> (define foo (make-mutable-thing 47))
	> (foo 'fetch)
	> (foo 'set! 53)
	> (foo 'fetch)
	> (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)
	> (define mutable-thing-incrementor!
	    (lambda (x)
	      (let ((old (x 'fetch)))
	        (x 'set! (+ old 1)))))
	> (mutable-thing-incrementor! foo)
	> (mutable-thing-incrementor! foo)
	> (foo 'fetch)

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

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

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...


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
Silicon Graphics, Inc.
2011 N. Shoreline Blvd.		Phone: 415-933-1673  FAX: 415-933-0979
Mountain View, CA  94043	PP-ASEL-IA