18.4 Subtyping

 < Free Open Study > 



18.4 Subtyping

One of the reasons for the popularity of object-oriented programming styles is that they permit objects of many shapes to be manipulated by the same client code. For example, suppose that, in addition to the Counter objects defined above, we also create some objects with an additional method that allows them to be reset to their initial state (say, 1) at any time.

   ResetCounter = {get:UnitNat, inc:UnitUnit, reset:UnitUnit};   newResetCounter =     λ_:Unit. let x = ref 1 in                 {get   = λ_:Unit. !x,                  inc   = λ_:Unit. x:=succ(!x),                  reset = λ_:Unit. x:=1};  newResetCounter : Unit  ResetCounter 

Since ResetCounter has all the fields of Counter (plus one more), the record subtyping rule tells us that ResetCounter <: Counter. This means that client functions like inc3 that take counters as arguments can also safely be used with reset counters:

   rc = newResetCounter unit;  rc : ResetCounter   (inc3 rc; rc.reset unit; inc3 rc; rc.get unit);  4 : Nat 



 < 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