[racket] could somebody tell me how this code works?

From: Stephen Bloch (sbloch at adelphi.edu)
Date: Tue Oct 5 09:20:41 EDT 2010

On Oct 5, 2010, at 7:30 AM, 김태윤 wrote:

> #lang racket
> (require 2htdp/image)
> (require 2htdp/universe)
> (define (handle-draw model) (text model 18 "blue"))
> (define (handle-key old-model key) key)
> (big-bang ""                           ; initial model is empty string
>          (check-with string?)         ; model is a string
>          (on-draw handle-draw 400 50) ; display text in 150x50 pixel window
>          (on-key handle-key))
> 
> could somebody please tell me how this code exactly work?
> my guessing is this 
> 
> there is only one checking function. 
> if it is true, keep big-bang going. 
> if it is false, it stops.

Not exactly: the "check-with" is just to catch programming errors, and to document that the model is supposed to be a string.  If I made a mistake, and my key handler returned something other than a string, it would catch that mistake.

> the first argument of big-bang "" is going to be sent to handle-draw by on-draw
> if key pressed, that handle-draw's return value is going to be sent to handle-key as second argument by on-key
> big-bang's first argument "" is changed to the handle-key's return value.
> and big-bang start again from the beginning with that value as first argument
> 
> I still have no idea about the old-model argument.

That's sort of right, but a confusing way to look at it.  Here's a simpler way.

At all times, there is a "model", which is initially the first argument of big-bang.
Every time a key is pressed, the key handler is called with the current model and the key; whatever the key handler returns becomes the new model.
Every time the model changes (for example, after the key handler returns), the draw handler is called with the current model; whatever the draw handler returns is shown on the screen.

> is check-with function must be there?

No, this animation would still work without the (check-with string?) .

Matthias pointed you to one place to read about this.  Another is at http://www.picturingprograms.com/pdf/chap06.pdf .


Stephen Bloch
sbloch at adelphi.edu



Posted on the users mailing list.