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_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;
    function stackSize return integer;
    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
          item : list;
          top : natural := 0;
      end record;
  st : ob_stack;

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

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

  function stack_is_empty return boolean is
      return = 0;
  end stack_is_empty;

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

  function stackSize return integer is
  end stackSize;

  procedure reset_stack is
  begin := 0;
  end reset_stack;
end gstack;

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


Leave a Reply

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

You are commenting using your 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