Subject: Re: YASOS: closures/code sharing
From: rpw3@rigden.engr.sgi.com (Rob Warnock)
Date: 1998/05/30
Newsgroups: comp.lang.scheme
Message-ID: <6ko1gt$369dh@fido.engr.sgi.com>

Jost Boekemeier  <jostobfe@apfel.zrz.TU-Berlin.DE> wrote:
+---------------
| cmmike@my-dejanews.com writes:
| > eq? says #f because you are comparing different _closures_.  The code
| > inside really is the same...
...
| But code sharing is not all I need; I still think that an object
| system which uses real inheritance (instead of delegation) needs a class
| where code *and* constants are stored...
+---------------

Well, given closures, you don't really need "classes" per se to get
shared constants/variables. If you write a Scheme function that returns
closures that have more than one level of environment, even though the
individual *final* closures may be different, besides sharing the code
they *will* also share any other data in the environment (that is, args
to higher-level closures, which can be thought of as "super-classes" in
this context). This is one way you can build "objects" in classical Scheme.
For example:

	> (define (make-shared-string+private-number-maker s)
	    (lambda (n)
	      (lambda (op . rest)
	        (case op
		  ((number) n)
		  ((number!) (set! n (car rest)) n)
		  ((string) s)
		  ((string!) (set! s (car rest)) s)
		  (else
		    (error "Unimplemented SS+PN operation:" op))))))

	> (define shared-hello+PN-maker
	    (make-shared-string+private-number-maker "hello there!"))
	> (define Shello+P3 (shared-hello+PN-maker 3))
	> (define Shello+P17 (shared-hello+PN-maker 17))

So now:

	> (Shello+P3 'n)
	Unimplemented SS+PN operation: n
	> (Shello+P3 'number)
	3
	> (Shello+P3 'string)
	"hello there!"
	> (Shello+P17 'number)
	17
	> (Shello+P17 'string)
	"hello there!"

and even though the "outer" closures are different the "inner" closures
and their data are the same:

	> (eq? Shello+P3 Shello+P17)
	#f
	> (eq? (Shello+P3 'string) (Shello+P17 'string))
	#t

And what's more, you can change the shared state:

	> (Shello+P17 'string! "let's change the string!")
	"let's change the string!"
	> (Shello+P3 'string)
	"let's change the string!"
	> (eq? (Shello+P3 'string) (Shello+P17 'string))
	#t

[Of course, with these "objects" you can also change the unshared state.
Exercise for the reader.]


-Rob

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