[plt-scheme] Structure design, Immutable vs Mutable

From: Henk Boom (lunarc.lists at gmail.com)
Date: Thu Sep 27 12:36:05 EDT 2007

On 26/09/2007, Matthias Felleisen <matthias at ccs.neu.edu> wrote:
> I teach this functional approach to games in my CS1 course here
> at Northeastern. Your game idea looks familiar and it wouldn't
> pose any undue problems in the framework I have designed. See
>   http://www.ccs.neu.edu/home/matthias/HtDP/Prologue/book.html
> for a loose description of the interface or look in Help Desk
> for the world.ss teachpack.
> ...

Thank you, I will take a look.

> One specific point: I don't understand why you speak of subtypes
> in your message. I consider this issue entirely orthogonal.

Okay, maybe I wasn't clear enough, let me give a concrete example. My
world has physical boundaries which the bodies and player must not
leave. I would implement this by writing a clamp procedure which I
call on the bodies after updating them.

(define-struct body (position velocity))
(define-struct player body (orientation))

;clamp: body boundary -> body
(define (clamp body boundary)
  (let ((position (body-position body)))
      ((outsite? boundary position)
          (nearest-inside boundary position)
          (body-velocity body))))
      (else body))))

clamp would bring bodies into the boundaries, but when I call it
giving a player as an argument, it does not return a player! I could
get around this by using the class.ss library and overloading the
clamp method, but then I will have to overload it in subclasses even
when they don't conceptually change the behaviour (especially since I
have plans for more types than just body and player). 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.

> Finally: I am also writing the second volume of HtDP (called How
> to Design Classes) with this style. It turns out that in a CBPL
> (aka OOPL) such an applicative (pure, functional) approach is
> notationally even more economic than in a pure FPL.

One of the sections I found somewhat lacking in HtDP was how to decide
when to use immutable or mutable structures, I hope HtDC will talk
more about that. =)

    Henk Boom

Posted on the users mailing list.