[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: set in Scheme?
In article <1822@uhccux.UUCP> chin@uhccux.UUCP (David Chin) writes:
>Does anyone know how to do the equivalent of a Common Lisp "set" in
>Scheme. In particular, I would like to be able to pass different
>symbols as arguments to a function and then set! or define them inside
Standard (R3RS) Scheme does not have anything of this sort.
>Is this style of programming (global side-effects for
>function calls) contrary to the Scheme philosophy?
What you can do in Scheme is to use a different abstraction rather
than passing symbols to set. For example:
(define (make-cell contents)
(define (cell-contents cell) (car cell))
(define (set-cell-contents! cell new-contents)
(set-car! cell new-contents))
Instead of passing a symbol, you would give the symbol a cell as its
value and pass the value of the symbol (the cell). Set-cell-contents!
could then be used to change the value in the cell.
So: (define (set-three! cell) (set-cell-contents! call 3))
(define x (make-cell 2))
Then (cell-contents x) ==> 3.
An alternative approach would be to pass a function instead of the symbol.
This function could be called to get or set the symbol's value. This can
be made to look nicer by using macros. The code below is meant to look
a bit like "locatives" in T:
(defmacro (symbol-locative sym)
(let ((temp-name (different-symbol sym)))
(lambda () ,sym)
(lambda (,temp-name) (set! ,sym ,temp-name)))))
(define (different-symbol s)
(if (eq? s 'x) 'y 'x))
(define (make-symbol-locative get-thunk set!-thunk)
(cond ((eq? message 'get) get-thunk)
((eq? message 'set!) set!-thunk))))
(define (contents locative)
(define (set-contents! locative new-contents)
((locative 'set!) new-contents))
The example again:
(define set-three! (loc) (set-contents! loc 3))
(define x 2)
(set-three (symbol-locative x))
Then x ==> 3.
Jeff Dalton, JANET: J.Dalton@uk.ac.ed
AI Applications Institute, ARPA: J.Daltonemail@example.com
Edinburgh University. UUCP: ...!ukc!ed.ac.uk!J.Dalton