[plt-scheme] with-struct

From: Eli Barzilay (eli at barzilay.org)
Date: Wed Oct 21 14:50:11 EDT 2009

On Oct 21, Jon Rafkind wrote:
> Here is a macro that introduces fields of a struct into the current
> lexical environment so that instead of saying (foo-x some-foo) you
> can just say 'x', similar to pascal's `with' construct.
> I had to resort to string munging to get the original field
> names. Is there a better way? I guess the "right" answer is to make
> the user pass in the field names themselves but I dislike such
> verbosity.

The right answer, IMO, and if this was desirable, is to make the
struct information include the field names, which would probably not
even be too much work.

But I don't think that this is a good idea.  If anything, then I think
that an extension to `define-struct' works out better.  For example
(using a horrible name):

  (define-struct foo (n m b) #:mutable #:with-scoper)
  (let ([my-foo (make-foo 1 2 3)])
    (with-foo my-foo
      (set! n 9)
      (printf "n is ~a\n" n)))

And BTW, that's one of the first fights I had with the then-new module
system and Swindle -- I used to have a `with-slots' macro that did
just the above dynamically, and it was a bad idea for obvious reasons.
I eventually made it accept the identifiers that you want in scope,
which seems much cleaner.  You can also think about not wanting all of
the bindings for these (for example, don't expose some field that is
holding some computed value), or using the same thing to deal with
struct-like values (which I implemented in the form of

          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                    http://barzilay.org/                   Maze is Life!

Posted on the users mailing list.