0.2 Manipulating the stack

You will often find that the items on the stack are not in the right order or that you need a copy. There are stack-manipulators which can take care of that.

To display a number you use '.', pronounced "dot". It takes a number from the stack and displays it. 'SWAP' reverses the order of two items on the stack. If we enter:

     2 3 . . cr

4tH answers:

     3 2

However, if you want to display the numbers in the same order as you entered them, you have to enter:

     2 3 swap . . cr

In that case 4tH will answer:

     2 3

You can duplicate a number using 'DUP'. If you enter:

     2 . . cr

4tH will complain that the stack is empty. However if you enter:

     2 dup . . cr

4tH will display:

     2 2

Another way to duplicate a number is using 'OVER'. In that case not the topmost number of the stack is duplicated, but the number beneath. E.g.

     2 3 dup . . . cr

will give you the following result:

     3 3 2

But this one:

     2 3 over . . . cr

will give you:

     2 3 2

Sometimes you want to discard a number, e.g. you duplicated it to check a condition, but since the test failed, you don't need it anymore. 'DROP' is the word we use to discard numbers. So this:

     2 3 drop .

will give you "2" instead of "3", since we dropped the "3".

The final one I want to introduce is 'ROT'. Most users find 'ROT' the most complex one since it has its effects deep in the stack. The thirdmost item to be exact. This item is taken from its place and put on top of the stack. It is 'rotated', as this small program will show you:

     1 2 3                                \ 1 is the thirdmost item
     . . . cr                             \ display all numbers
     ( This will display '3 2 1' as expected)
     1 2 3                                \ same numbers stacked
     rot                                  \ performs a 'ROT'
     . . . cr                             \ same operation
     ( This will display '1 3 2'!)