Changing The Stack

The stack can be changed in three ways. It can be enlarged, reduced or rearanged. All this can be done with the following words:

DROP ( n) Throw away the top of stack.

SWAP( nn'-n'n) Reverse the two top elements.

OVER ( n'n-n'nn') Copy of the second element on top.

ROT ( nln2n3-n2n3nl) Rotate the top three elements counter-clock wise.

Fig 3-1 shows how these words affect the stack.

SWAP

DROP

OVER

Fig 3-1 Changing the stack.

Now let us do some examples and exercises. Example 1:

The stack contains the numbers 3 2 1 with the 1 on top of the stack. What words must be entered to obtain the sequence 3 2 2 1?

First we enter OVER and get 3 2 12. Second we enter SWAP to obtain the result 3 2 2 1 .

Example 2:

On the stack we have 3 2 1 with the 1 on top of the stack. Which words must be entered to get the sequence 2 3 3? The answer is shown below.

DROP 3 2

SWAP 2 3

Exercise: Start with and get a)

3 2 1 on the stack

The word .S ( dot s, print stack) shown in Fig 3-2 is very usefull. It is defined in most of the FORTH versions and prints the contents of the stack without destroying it. If your FORTH version doesn't know this word just type it in.

DEEP SO @ 'S - 2 / 1 - ; .S CR DEEP 'S 2 - SO @ 2 -DO I @ . -2 +LOOP ELSE ." EMPTY" THEN ;

Fig 3-2 Non-destructive stack print.

0 0

Post a comment

  • Receive news updates via email from this site