Concepts of Programming Languages

(Sean Pound) #1

504 Chapter 11 Abstract Data Types and Encapsulation Constructs


The Ada stack abstract data type example shown in Section 11.4.1 suffers
two restrictions: (1) Stacks of its type can store only integer type elements, and
(2) the stacks can have only up to 100 elements. Both of these restrictions can
be eliminated by using a generic package, which can be instantiated for other
element types and any desirable size. (This is a generic instantiation, which is
very different from the instantiation of a class to create an object.) The follow-
ing package specification describes the interface of a generic stack abstract data
type with these features:

generic
Max_Size : Positive; -- A generic parameter for stack
-- size
type Element_Type is private; -- A generic parameter
-- for element type
package Generic_Stack is
-- The visible entities, or public interface
type Stack_Type is limited private;
function Empty(Stk : in Stack_Type) return Boolean;
procedure Push(Stk : in out Stack_Type;
Element : in Element_Type);
procedure Pop(Stk : in out Stack_Type);
function Top(Stk : in Stack_Type) return Element_Type;
-- The hidden part
private
type List_Type is array (1..Max_Size) of Element_Type;
type Stack_Type is
record
List : List_Type;
Topsub : Integer range 0..Max_Size := 0;
end record;
end Generic_Stack;

The body package for Generic_Stack is the same as the body package for
Stack_Pack in the Section 11.4.1.3 except that the type of the Element for-
mal parameter in Push and Top is Element_Type instead of Integer.
The following statement instantiates Generic_Stack for a stack of 100
Integer type elements:

package Integer_Stack is new Generic_Stack(100, Integer);

One could also build an abstract data type for a stack of length 500 for Float
elements, as in

package Float_Stack is new Generic_Stack(500, Float);

These instantiations build two different source code versions of the
Generic_Stack package at compile time.
Free download pdf