[plt-scheme] redefining set!

From: Carl Eastlund (cce at ccs.neu.edu)
Date: Mon Jun 18 16:14:32 EDT 2007

When DrScheme encounters a reference to the builtin set!, such as
(set! variable expression), it looks up the variable and expands based
on that.  So if you have some variable and you want it to represent
communication on a port, for instance, you could write the following:

(define the-port (open-input-file "the-file.txt"))

(define-syntax comm
  (make-set!-transformer
    (lambda (stx)
      (syntax-case stx (set!)
        [(set! id expr) (syntax (write expr the-port))]
        [id (identifier? (syntax id)) (syntax (read the-port))]
        [_ (raise-syntax-error #f "not an operator" stx)]))))

This makes comm a macro.  When used in set!, it writes to
the-file.txt.  When used as a variable reference, it reads from
the-file.txt.  Any other use is a syntax error.  Unlike redefining
set! (as Jens has just posted), set! will still work normally for
every other identifier.  It has only changed for comm.  This may be
the kind of context sensitive behavior you need.  If not, go with what
Jens wrote.

On 6/18/07, Hans Oesterholt-Dijkema <hdnews at gawab.com> wrote:
> I looked, but I don't exactly understand what the documentation
> is trying to tell me.
>
> --Hans
>
>
> Carl Eastlund schreef:
> > On 6/18/07, Hans Oesterholt-Dijkema <hdnews at gawab.com> wrote:
> >> Is it possible to redefine, or override set!?
> >> I'd like to extend the behaviour of the set!
> >> operator to act context sensitive.
> >
> > It is possible to bind some other syntax or value to the identifier
> > set!, but it is also possible to define set!'s behavior on other
> > identifiers using make-set!-transformer.  You may want to do that
> > instead of changing set! itself.  Look up make-set!-transformer in
> > Help Desk.


Posted on the users mailing list.