[racket] Advice: simulating stateful API in functional setting

From: Mark Engelberg (mark.engelberg at gmail.com)
Date: Sat Jul 16 14:12:30 EDT 2011

On Sat, Jul 16, 2011 at 7:33 AM, Stephen Bloch <sbloch at adelphi.edu> wrote:
> These functions would presumably maintain the invariant that each name corresponds to at most one sprite in a world.  Letting the kids manipulate the list of sprites directly does NOT maintain that invariant, so I think I have to do one or the other: either show the kids the list and let them do what they will, or hide the list and provide only accessors to it.

Yes, you are right that when I said "let the kids manipulate the world
directly", I meant that they manipulate the world with functions that
enforce certain invariants.  So yes, I was thinking that add-sprite
would return an error if they try to add a sprite with the same name
as one already in the list.

I don't think I agree with the idea that if you let kids see the
internals of the world structure, you must allow them to program to
the internals of the world structure.  I personally would be okay with
making it all visible so that it's easier to understand, test, and
debug, and then say, "But it's hard to manage this kind of complex
information without relying on helper functions that maintain certain
invariants."  Nevertheless, I see your point, especially from a "do it
on a first day perspective".  With that in mind, making the world
structure more opaque might be desirable.

The resulting user code using the formulation with strings for sprite
names looks very similar to your original formulation, with the
exception of forcing the programmer to restate the sprite name in
every instruction, even in the common case where you only want to
manipulate one sprite.  I can think of ways to make this look nicer
using macros, but can't think of any way that wouldn't seem like "too
much magic" for a beginner programmer.

The closest idea I have is to make it so all the built-in drawing
functions optionally can take one less parameter (i.e., not the sprite
name), in which case the instruction applies to the first sprite in
the sprite list.  This would make it possible to avoid mentioning the
sprite name if you only add one sprite to the world.



Posted on the users mailing list.