Rexx - Stacks


Advertisements


The stack is sometimes called the external data queue, but we follow common usage and refer to it as the stack. It is a block of memory that is logically external to Rexx. Instructions like push and queue place data into the stack, and instructions like pull and parse pull extract data from it. The queued built-in function reports how many items are in the stack.

Let’s take a look at an example of a stack.

/* STACK: */
/* */ 
/* This program shows how to use the Rexx Stack as either a */ 

/* stack or a queue. */ 
do j = 1 to 3 
push ‘Stack: line #’ || j 

/* push 3 lines onto the stack */ 
end 
do j = 1 to queued() 

/* retrieve and display LIFO */ 
pull line 
say line 
end 
do j = 1 to 3 queue ‘Queue: line #’ || j 

/* queue 3 lines onto the stack */ 
end 
do queued() 

/* retrieve and display FIFO */ 
pull line 
say line 
end 
exit 0

The first do loop in the program places three lines of data onto the stack. It uses the push instruction to do this. We number the lines so that when they are retrieved in the LIFO order their order is apparent.

The items placed into the stack by the push instruction are retrieved in the LIFO order −

do j = 1 to 3 
push ‘Stack: line #’ || j /* push 3 lines onto the stack */ 
end

The next code block shows the use of the queued built-in function to discover the number of lines on the stack, as well as a loop to retrieve all the lines from the stack −

do j = 1 to queued()  /* retrieve and display LIFO */ 
pull line 
say line 
end

Since the three items were placed on the stack via push, they are retrieved in the LIFO order.

The output of the above program will be as follows.

STACK: LINE #3 
STACK: LINE #2 
STACK: LINE #1   


Advertisements