18.9 Classes with Self

 < Free Open Study > 



18.9 Classes with Self

Our final extension is allowing the methods of classes to refer to each other via self. To motivate this extension, suppose that we want to implement a class of counters with a set method that can be used from the outside to set the current count to a particular number.

   SetCounter = {get:UnitNat, set:NatUnit, inc:UnitUnit}; 

Moreover, suppose that we want the inc method in terms of set and get, rather than directly reading and assigning the instance variable x. (Imagine a much larger example in which the definitions of set and get each take many pages.) Since get, set, and inc are all defined in the same class, what we are asking for is essentially to make the methods of this class mutually recursive.

We saw how to build mutually recursive records of functions using the fix operator in §11.11. We simply abstract the record of methods on a parameter that is itself a record of functions (which we call self), and then use the fix operator to "tie the knot," arranging that the very record we are constructing is the one passed as self.

   setCounterClass =     λCounterRep.       fix         (λself: SetCounter.           {get = λ_:Unit. !(r.x),            set = λi:Nat.  r.x:=i,            inc = λ_:Unit. self.set (succ (self.get unit))});  setCounterClass : CounterRep  SetCounter 

This class has no parent class, so there is no need for a super variable. Instead, the body of the inc method invokes get and then set from the record of methods passed to it as self. This use of fix is entirely internal to setCounterClass. We then create set-counters in exactly the same way as usual.

   newSetCounter =     λ_:Unit. let r = {x=ref 1} in                 setCounterClass r;  newSetCounter : Unit  SetCounter 



 < 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