Ada : Generic stacks (i)

A very nice feature of Ada is the ability to create generic data types – nice for code reuse. For example the size of each stack and the type of the stack elements can be provided as generic parameters. A generic stack is created using some of Ada’s OO -type features, and stored in an Ada package. Here is the package “header” stack.ads:

generic 
    stack_size : integer;
    type object is private;
package gstack is
    procedure push(x : in object);
    procedure pop(x : out object);
    function stack_is_empty return boolean;
    function stack_top return object;
    procedure reset_stack;
end gstack;

It contains the usual series of functions needed to implement a stack. Note however that there is no type specified for the object being stored except the keyword object. Note also the use of the keyword generic to specify that the specific type will be acknowledged later. Here are the contents of the associated stack.adb file:

with Ada.Text_IO;
use Ada.Text_IO;

package body gstack is
  type list is array(1..stack_size) of object;
  type ob_stack is
      record
          item : list;
          top : natural := 0;
      end record;
  st : ob_stack;

  procedure push(x : in object) is
  begin
      if st.top = 100 then
          put_line("stack is full");
      else
          st.top := st.top + 1;
          st.item(st.top) := x;
      end if;
  end push;

  procedure pop(x : out object) is
  begin
      if st.top = 0 then
          put_line("stack is empty");
      else
          x := st.item(st.top);
          st.top := st.top - 1;
      end if;
  end pop;

  function stack_is_empty return boolean is
  begin
      return st.top = 0;
  end stack_is_empty;

  function stack_top return object is
  begin
      if st.top = 0 then
          put_line("stack is empty");
          --return ' ';
      else
          return st.item(st.top);
      end if;
  end stack_top;

  procedure reset_stack is
  begin
      st.top := 0;
  end reset_stack;
end gstack;

In a follow-up post, I’ll look at how this can be used.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s