[racket] Programmatically start a big-bang?

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sun Apr 21 12:00:38 EDT 2013

Here is a sketch: 

#lang racket/gui

(require 2htdp/private/world 2htdp/image)

;; -----------------------------------------------------------------------------
;; small adapter 

(define (my-bb world0 ht)
  (lambda ()
    (new world% 
         (world0 world0)
         (on-draw    (hash-ref ht 'to-draw))
         (on-tick    (hash-ref ht 'on-tick))
         (on-mouse   (hash-ref ht 'on-mouse void))
         (on-key     (hash-ref ht 'on-key void))
         (record?    (hash-ref ht 'on-key #f))
         (stop-when  (hash-ref ht 'stop-when (lambda _ (displayln _) (lambda _ #f))))
         (state      (hash-ref ht 'state #f))
         (check-with (hash-ref ht 'check-with (lambda _ (lambda _ #t))))
         (on-release (hash-ref ht 'on-release void))
         (on-pad     (hash-ref ht 'on-pad #f))
         (name       (hash-ref ht 'name "no  name"))
         (register   (hash-ref ht 'register #f))
         (on-receive (hash-ref ht 'on-receive void))

;; (-> Object) -> Any
(define (run-it o)
  (define esp (make-eventspace))
  (define thd (eventspace-handler-thread esp))
  (with-handlers ((exn:break? (lambda (x) (break-thread thd))))
    (define obj:ch (make-channel))
    (parameterize ([current-eventspace esp])
      (queue-callback (lambda () (displayln o) (channel-put obj:ch (o)))))
    (send (channel-get obj:ch) last)))

;; -----------------------------------------------------------------------------
;; use: 

(define ht
   (list (cons 'to-draw (lambda (x) (circle (+ 10 x) 'solid 'red)))
         (cons 'on-tick sub1)
         (cons 'stop-when zero?))))

(define (tee tag x)
  (displayln `(tag ,x))

(run-it (my-bb 10 ht))

On Apr 21, 2013, at 11:04 AM, Joe Gibbs Politz wrote:

> I'd like to write a library function that takes a hash table of
> handlers and starts a running world in big-bang style, for example:
> (my-big-bang
> 0
> (make-immutable-hash
>  `((on-tick . ,add1)
>    (stop-when . ,(lambda (x) (> x 100))))))
> Is there an interface that I could use to write this?  I suppose I
> could try to generate a syntax object containing an appropriate
> big-bang and eval it, but that seems like a big hammer to wield here.
> I've poked around a little bit in 2htdp/ but haven't found anything
> provided that seems to fit the bill.
> Motivation: I want to support big-bang in a language that doesn't
> support macros (yet), and I don't want to add special-case syntax for
> big-bang.  I'd like the usage in that language (Pyret, which has
> Python-like syntax) to look like:
> big-bang(init, {
>  event_name: event_handler,
>  ...
> })
> Which calls something like `my-big-bang` under the hood.
> Thanks!
> Joe
> ____________________
>  Racket Users list:
>  http://lists.racket-lang.org/users

Posted on the users mailing list.