[plt-scheme] Structure design, Immutable vs Mutable

From: Henk Boom (lunarc.lists at gmail.com)
Date: Fri Sep 28 21:41:26 EDT 2007

On 27/09/2007, Matthias Felleisen <matthias at ccs.neu.edu> wrote:
> On Sep 27, 2007, at 12:36 PM, Henk Boom wrote:
>
> > I guess what I'm
> > looking for is a way to "make a copy of body with the position field
> > changed" which works even for structures extending body.
>
> Amen! I have been programming around this for a while, and
> Ryan has provided us with the tools to add this capability
> to the class system. We should be able to program in an
> applicative (more than normal) way soon.
>
> I understand your diagnosis now.

I've been fooling around in the documentation, and saw some things
which looked useful. The following seems to work, but I don't know
enough about inspectors to know if it's a good idea or not.

(module copy mzscheme
  (require (lib "class.ss"))

  (define body%
    (class object%
      (inspect #f)
      (init (copy-from #f))
      (init-field (position (if copy-from
                              (get-field position copy-from)
                              (list 0 0))))
      (super-new)))

  (define player%
    (class body%
      (inspect #f)
      (init (copy-from #f))
      (init-field (orientation (if copy-from
                                 (get-field orientation copy-from)
                                 0)))
      (super-new (copy-from copy-from))))

  (define-syntax modify
    (syntax-rules ()
      ((modify object (field value) ...)
       (new (call-with-values (lambda () (object-info object))
                              (lambda (class dummy)
                                class))
         (copy-from object)
         (field value) ...))))

  (define player (new player% (position '(1 2))
                              (orientation 90)))

  (define player2 (modify player (position '(42 1))))

  (printf "player: position=~a, orientation=~a~n"
          (get-field position player)
          (get-field orientation player))
  (printf "player2: position=~a, orientation=~a~n"
          (get-field position player2)
          (get-field orientation player2))

  ) ;; end module

Which outputs:
player: position=(1 2), orientation=90
player2: position=(42 1), orientation=90

Of course, the default-expressions for the init-fields could be macroized.

Does this look like a good idea?

    Henk Boom


Posted on the users mailing list.