Counter

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:


Variation

Java programmers and others may miss constructor methods in the class definition. In fact, counter itself has the role played by constructor methods as seen from the usage indication above. To, hopefully, make this clearer we note that one might want to create counter objects with some other initial value than 0. We can easily achieve this by a slight modification of counter:
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 0
and get a class counter with the same usage as our original definition.