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
goblins[1]>

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])
  (case-lambda
    (()         ; get
     val)
    ((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”!)

bcom also has an optional second argument which is used when we wish to return a value. Let’s take that cell actor from before. If we want to return the new value after setting it, we can do that by specifying the optional second argument to bcom:

(define* (^cell bcom #:optional [val #f])
  (case-lambda
    (()         ; get
     val)
    ((new-val)  ; set
     (bcom (^cell bcom new-val)
           new-val)))) ; Return new-val as the response

Let’s do the same invocation as before. This time, when we put a value in the cell, we also see it returned:

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

Next: Methods aren’t essential, but they are useful, Previous: A simple greeter, Up: Tutorial   [Contents][Index]