Open recursion (late binding of self) Types and Programming Languages Benjamin C. Pierce MIT Press, 2002. Chapter 18. Case Study: Imperative Objects 18.9 Classes with Self % This is NOT late binding of self, but early binding of self CounterRep = {x:int ref}; SetCounter = {get:1 -> int, set:int -> 1, inc:1 -> 1}; setCounterClass : CounterRep -> SetCounter = lam r:CounterRep. fix self:SetCounter. {get = lam _:1. !(r.x), set = lam i:int. r.x := i, inc = lam _:1. self.set (self.get() + 1)}; newSetCounter : Unit -> SetCounter = lam _:1. let r = {x = ref 1} in setCounterClass r end; 18.10 Open Recursion through Self % Move the fixpoint from class definition to object creation setCounterClass : CounterRep -> SetCounter -> SetCounter = lam r:CounterRep. lam self:SetCounter. {get = lam _:1. !(r.x), set = lam i:int. r.x := i, inc = lam _:1. self.set (self.get() + 1)}; newSetCounter : Unit -> SetCounter = lam _:1. let r = {x = ref 1} in fix self. setCounterClass r self end; InstrCounterRep = {x:int ref, a:int ref} InstrCounter = {get:1 -> int, set:int -> 1, inc:1 -> 1, accesses:1 -> int} instrCounterClass : InstrCounterRep -> InstrCounter -> InstrCounter = lam r:InstrCounterRep. lam self:InstrCounter. let super = setCounterClass r self in {get = super.get, set = lam i:int. (r.a := !(r.a)+1; super.set i), inc = super.inc, accesses = lam _:1. !(r.a)} end; 18.11 Open Recursion and Evaluation Order % The following has termination problems newInstrCounter : 1 -> InstrCounter = lam _:1. let r = {x=ref 1, a=ref 0} in fix self. instrCounterClass r self end;