MyRPL-Example. Reverse data in the stack


Reverse data position using an auxiliary LIST.

Suppose that you have the following data in the stack:

5: 50
4: 40
3: 30
2: 20
1: 10

You need to reverse the data and obtain:

5: 10
4: 20
3: 30
2: 40
1: 50

How to design a program to do this?

1. Data could be sent to a list.
The command to do this is ->LIST.

The command ->LIST needs to know the stack size. In this case the stack size is 5.

The command DEPTH is used to return the stack size to the first stack level.

Then:
DEPTH
LIST

will obtain:  { 50 40 30 20 10 }

2. Later when the list is created we could use the GET command for each list element from
right to left in the list.

So, we shall begin with the fifth element of the list. 
5 GET will obtain: 10
Then put 10 on the stack
4 GET will obtain: 20
Then put 20 on the stack 
3 GET will obtain: 30
Then put 30 on the stack
2 GET will obtain: 40
Then put 20 on the stack 
1 GET will obtain: 10
Then put 10 on the stack

The result will be:

5: 10
4: 20
3: 30
2: 40
1: 50

We need to save the list to some variable. For example: MYLIST.
We need an iteration ( a cycle ) through the list ( five times ). The iterator could be the variable I.

The cycle will be controlled by a START NEXT structure. START - NEXT will be executed from 1 to 5.

The complete program will be:
 
DEPTH
DUP
'I'
STO
->LIST
'MYLIST'
STO
1
I
START
MYLIST
I
GET
I
1
-
'I'
STO
NEXT


Note that the iterator decrements from 5 to 1.



In MyRPL is possible to write the program using lowercase.
I wrote the program at hand on the program grid.

Before I inserted some empty lines using the INSERT key.

The program could be written in a variable.

This time I used uppercase.

The same program written in a HP50G and tested OK.