The Counter example is a minimal example of a class from which one can instantiate objects with state. Several variations are possible; here is the one we choose:
module Counter where
struct Counter where
incr :: Action
decr :: Action
value :: Request Int
counter = class
n := 0
incr = action n := n+1
decr = action n := n-1
value = request result n
result Counter{..}
Comments:
ctr = new counterThe variable ctr has type Counter, and the newly created object can be updated by method calls ctr.incr and ctr.decr. The state can be read by
val <- ctr.value
counter = class
n := 0
result
struct
incr = action n := n+1
decr = action n := n-1
value = request result n
In more complex situations, the {..} is a useful convenience.
counterInit init = class n := init ...The rest of the class is as before. To create an object with initial value 5, we would write
ctr = new counterInit 5
Thus, we have the typing counterInit :: Int -> Class Counter.
We might still keep the definition of counter, but this would mean code duplication that should be avoided. Instead, we could write
counter = counterInit 0and get a class counter with the same usage as our original definition.