PPP Exercises: Programming Styles and Abstract Data Types


Exercise: Functional Abstract Data Type

Write an implementation 'count' for this functional abstract data type:
Let Count =
   Tuple
      T <:Ok
         (* Sort of Abstract Data Type 'Count' *)
      new(:Int) :T
         (* creates a counter with an initial state *)
      inc(:T) :T
         (* increments the counter and returns a new (abstract) value *)
      get(:T) :Int
         (* gets value of counter *)
   end;
Test with:
count.get(count.inc(count.new(5)));

Exercise: Imperative Abstract Data Type

Write an implementation 'count' for this imperative abstract data type. Hint: The counter's state has to be stored somewhere in a (mutable) variable. Note that TL does not support first-class mutable variables.
Let Count =
   Tuple
      T <:Ok
         (* Sort of Abstract Data Type 'Count' *)
      new(:Int) :T
         (* creates a counter with an initial state *)
      inc(:T) :Ok
         (* increments the counter (side-effect!) *)
      get(:T) :Int
         (* gets value of counter *)
   end;
Test with:
let aCounter = count.new(5);
count.inc(aCounter);
count.get(aCounter);

Exercise: Object-oriented Abstract Data Type

Write an implementation 'count' for this object-oriented abstract data type. Hint: Like in the previous exercise, the counter's state has to be stored somewhere in a variable. Where exactly this variable should be declared, is the main problem of this exercise. The TL block construct 'begin ... tuple ... end end' might be useful when implementing the function 'new'.
Let Count =
   Tuple
      Let T =
         Tuple
            inc() :Ok
              (* increments the counter (side-effect!) *)
            get() :Int
              (* gets value of counter *)
         end
      new(:Int) :T
         (* creates a counter with an initial state *)
   end;
Test with:
let aCounter = count.new(5);
aCounter.inc();
aCounter.get();

Ulrike Steffens, 1994