[plt-scheme] Mutation and worlds with world/universe.ss

From: Nadeem Abdul Hamid (nadeem at acm.org)
Date: Fri Nov 13 21:53:30 EST 2009

It seems like the world/universe.ss teachpacks optimize things so that  
if the world structure has not changed, the window is not redrawn.  
This causes difficulty when the world is updated via mutation; for  
example, consider:

;; A Board is an N x N, Vector-of-Vector-of-Boolean

;; A World is a structure: (make-world Board)
(define-struct world (board))

...

;; handle-click : World Number Number MouseEv -> World
(define (handle-click w x y me)
   (local [(define p (x/y->cell (world-board w) x y))]
     (cond [(mouse=? me "button-down")
            (begin (board-flip! (world-board w) (posn-x p) (posn-y p))
                   w)]
           [else w])))

(big-bang (make-world TEST-BOARD)
           (on-draw draw-world)
           (on-mouse handle-click))


This does not update the display upon clicking in the window, although  
when you stop the animation, it can be seen that the state has in fact  
changed.

However, if the world is recreated in the handler with another piece  
of data that changes then the display gets updated as expected:

;; A World is a structure: (make-world Number Board)
(define-struct world (n board))

...

;; handle-click : World Number Number MouseEv -> World
(define (handle-click w x y me)
   (local [(define p (x/y->cell (world-board w) x y))]
     (cond [(mouse=? me "button-down")
            (begin (board-flip! (world-board w) (posn-x p) (posn-y p))
                   (make-world (add1 (world-n w)) (world-board w)))]
           [else w])))



Is there any way to handle this other than recreating a new world  
structure? Is there another better way to program worlds with mutation?

Thanks,
nadeem





Posted on the users mailing list.