Ada 95 :: x20_st_a.ada

package Class_stack is
  type Stack is private;                -- Copying allowed
  Stack_error: exception;               -- When error

  procedure reset( the:in out Stack);
  procedure push( the:in out Stack; item:in Integer );
  procedure pop(the:in out Stack; item :out Integer );
private

  MAX_STACK: CONSTANT := 3;
  type    Stack_index is range 0 .. MAX_STACK;
  subtype Stack_range is Stack_index range 1 .. MAX_STACK;
  type    Stack_array is array ( Stack_range ) of Integer;

  type Stack is record
    elements: Stack_array;          -- Array of elements
    tos     : Stack_index := 0;     -- Index
  end record;

end Class_stack;


package body Class_stack is

  procedure push( the:in out Stack; item:in Integer ) is
  begin
    if the.tos /= MAX_STACK then
      the.tos := the.tos + 1;               -- Next element
      the.elements( the.tos ) := item;      -- Move in
    else
      raise Stack_error;                    -- Failed
    end if;
  end push;

  procedure pop( the:in out Stack; item :out Integer ) is
  begin
    if the.tos > 0 then
      item := the.elements( the.tos );      -- Top element
      the.tos := the.tos - 1;               -- Move down
    else
      raise Stack_error;                    -- Failed
    end if;
  end pop;

  procedure reset( the:in out Stack ) is
  begin
    the.tos := 0;  -- Set TOS to 0 (Non existing element)
  end reset;

end Class_stack;

with Simple_io, Class_stack;
use  Simple_io, Class_stack;
procedure main is
  number_stack : Stack;              -- Stack of numbers
  action       : Character;          -- Action
  number       : Integer;            -- Number processed
begin
  while not end_of_file loop
    while not end_of_line loop
      begin
        get( action );
        case action is               -- Process action
          when '+' =>
            get( number ); push(number_stack,number);
            put("push number = "); put(number); new_line;
          when '-' =>
            pop(number_stack,number);
            put("Pop number  = "); put(number); new_line;
          when others =>
            put("Invalid action"); new_line;
        end case;
      exception
        when Stack_error =>
          put("Stack_error"); new_line;
        when Data_error  =>
          put("Not a number"); new_line;
        when End_error   =>
          put("Unexpected end of file"); new_line; exit;
      end;
    end loop;
    skip_Line;
  end loop;
  reset( number_stack );
end main;


© M.A.Smith University of Brighton. Created September 1995 last modified May 1997.
Comments, suggestions, etc. M.A.Smith@brighton.ac.uk * [Home page]