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


4.2 State as updating behavior

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

scheme> ,enter-vat a-vat
goblins[1]>

Let’s introduce 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])
  (case-lambda
    (()         ; get
     val)
    ((new-val)  ; set
     (bcom (^cell bcom new-val)))))

case-lambda allows for dispatching depending on the number of arguments, so here we’re choosing that if no arguments are provided, our 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, and so do treasure chests, so let’s 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 we 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”!)