Next: , Previous: , Up: Tutorial   [Contents][Index]

4.2 State as updating behavior

Re-enter a-vat’s subrepl if you haven’t:

scheme> ,enter-vat a-vat

Here is a simple cell which stores a value. This cell will have two methods: 'get retrieves the current value, and 'set replaces the current value with a new value.

(define* (^cell bcom #:optional [val #f])
    (()         ; get
    ((new-val)  ; set
     (bcom (^cell bcom new-val)))))

case-lambda allows for dispatching depending on the number of arguments, so this code says that if no arguments are provided, the cell shares the current value; and if one argument is provided, the cell updates itself to become a cell storing the new value.

Cells hold values. So do treasure chests. Make a treasure chest flavored cell. Taking things out and putting them back in is easy:

goblins[1]> (define chest
              (spawn ^cell "sword"))
goblins[1]> ($ chest)
; => "sword"
goblins[1]> ($ chest "gold")
goblins[1]> ($ chest)
; => "gold"

Now you can see what bcom is: a capability specific to this object instance which allows it to change its behavior! (For this reason, bcom is pronounced “become”!)