I finished it and here it is. a generic stack.
Spec:
with Ada.Finalization;
generic
package GenericStack is
type ElementType is private;
type Stack is new Ada.Finalization.Limited_Controlled with private;
procedure Finalize (S : in out Stack);
function IsEmpty (S : Stack) return Boolean;
procedure MakeEmpty (S : in out Stack);
procedure Pop (S : in out Stack);
procedure Push (S : in out Stack ; X : ElementType);
function TopOfStack(S : Stack) return ElementType;
private
type Cell;
type CellPtr is access Cell;
type Cell is
record
Element : ElementType;
Next : CellPtr;
end record;
type Stack is new Ada.Finalization.Limited_Controlled with
record
Top : CellPtr;
end record;
end GenericStack;
Body:
with Ada.Unchecked_Deallocation;
package body GenericStack is
procedure Clear is new Ada.Unchecked_Deallocation(Cell, CellPtr);
-- generic ada operation for freeing up memory
procedure Finalize (S : in out Stack) is
begin
MakeEmpty (S);
end Finalize;
function IsEmpty (S : Stack) return Boolean is
begin
return S.Top = null;
end IsEmpty;
procedure MakeEmpty (S : in out Stack) is
begin
while not IsEmpty(S) loop
Pop(S);
end loop;
end MakeEmpty;
procedure Pop (S : in out Stack) is
--Assumes Stack is not empty
FirstCell : CellPtr;
begin
if IsEmpty (S) then
null;
else
FirstCell := S.Top;
S.Top := S.Top.Next;
Clear(FirstCell);
end if;
end Pop;
procedure Push (S : in out Stack ; X : in ElementType) is
--assumes not out of memory
begin
S.Top := new Cell'(Next => S.Top, Element => X);
end Push;
function TopOfStack(S : Stack) return ElementType is
-- Assumes not empty
begin
return S.Top.Element;
end TopOfStack;
end GenericStack;
example. integerstack.ads
with genericstack;
package IntegerStack is new genericstack(Integer);