32.6 Simple Classes

 < Free Open Study > 



32.6 Simple Classes

Now let us consider classes, beginning (as we did in Chapter 18) with simple classes without self.

In §18.6, we defined a simple class (for the imperative object encoding, where objects were records of methods) to be a function from states to objects-a way of manufacturing multiple objects with the same methods but each with a freshly allocated set of instance variables. In this chapter, an object is more than just a record of methods: it includes a representation type and a state as well. On the other hand, since this is a purely functional model, each of the methods takes the state as a parameter (and, if necessary, returns an object with an updated state), so we don't need to pass the state to the class at object-creation time. In fact, a class here-given that we are still assuming that all objects use the same representation type-can be viewed as simply a record of methods,

   counterClass =      {get = λr:CounterR. r.x,       inc = λr:CounterR. {x=succ(r.x)}}   as {get: CounterRNat, inc:CounterRCounterR};  counterClass : {get:CounterRNat, inc:CounterRCounterR} 

or, using the CounterM operator to write the annotation more tersely:

   counterClass =      {get = λr:CounterR. r.x,       inc = λr:CounterR. {x=succ(r.x)}}      as CounterM CounterR;  counterClass : CounterM CounterR 

We build instances of such classes by supplying an initial value for the state and packaging this state with the methods (i.e., the class) into an object.

   c = {*CounterR,        {state = {x=0},         methods = counterClass}}       as Counter;  c : Counter 

Defining a subclass is simply a matter of building a new record of methods, copying some of its fields from a previously defined one.

   resetCounterClass =      let super = counterClass in      {get = super.get,       inc = super.inc,       reset = λr:CounterR. {x=0}}      as ResetCounterM CounterR;  resetCounterClass : ResetCounterM CounterR 

To generalize these simple classes to handle the same sorts of examples that we closed with in Chapter 18, two more things are needed: the ability to add new instance variables in subclasses, and a treatment of self. The next two sections address the first of these; §32.9 closes the chapter with a treatment of self.



 < Free Open Study > 



Types and Programming Languages
Types and Programming Languages
ISBN: 0262162091
EAN: 2147483647
Year: 2002
Pages: 262

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net