[racket] Advice: simulating stateful API in functional setting

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Sat Jul 16 10:55:54 EDT 2011

On Jul 16, 2011, at 10:34 AM, Matthias Felleisen wrote:

> Since these people have no scruples -- don't even understand that they dont have any -- go for the imperative version.

I have a hard time believing that EVERY CS educator who evangelizes for something other than PBD "has no scruples".  And for people like Dan Garcia who are not only gifted teachers but knowledgeable about functional programming, I'd rather try to persuade and find areas of mutual agreement.

>> Every workshop on Python or Processing in education includes an example ("which students can do on the first day," although largely by copying and tinkering rather than deep understanding) 
> We can do an animation on the first day. Our students actually understand what they do and why it works. And the idea is 100% algebra. So why cave? Why not attack them? 

Oh, map-image and build-image are clean and functional (at least from the student's perspective); I don't see them as "caving" at all.

I went to a talk at SIGCSE in which somebody posted one of these Python or Processing examples, so I opened DrRacket on my laptop, spent a minute re-coding it using build-image, then showed it to her (applied to her own face off her Web site) after the talk:

(define (diag-mirror pic)
	(build-image (image-width pic) (image-width pic)
				(lambda (x y)
					(if	(> x y)
						(get-pixel-color x y pic)
						(get-pixel-color y x pic)))))

Likewise, there's the Stone "random art" assignment from nifty.stanford.edu: it's easy to do in Python or Processing with nested for-loops, but it's even easier to do with build-image.  I think pretty much any example of this sort that you find in a Python or Processing book can be done with map-image, build-image, and function closures.

Replicating the BYOB exercises is more difficult, and I'm sure there will be heavily-imperative things that I can't translate into any kind of natural functional code, but I'd like to be able to translate a lot of the standard beginning exercises.

(Hmm... simulate "wait" by replacing the "action" of the current sprite with a function that checks the clock time and then invokes the current continuation....)

Stephen Bloch
sbloch at adelphi.edu

Posted on the users mailing list.