8th Tutorial

Lession 4: Manipulating the stack

Note: if you haven’t yet installed 8th, please do so right now and follow the installation instructions as presented in the manual!

Simple stack manipulations

In the previous lesson you learned about the stack in general. In this one you’ll learn some of the more common stack manipulation words.

Let’s learn by playing around with 8th. Start 8th, and in the console type

10 20 30 .s
3 n: ... 30 2 n: ... 20 1 n: ... 10
So you’ve got three numbers on the stack. Try the word “drop”:
drop .s
2 n: ... 20 1 n: ... 10
Apparently, it removes (or “drops”) an item from the stack. Try the word “dup”:
dup .s
3 n: ... 2 20 2 n: ... 2 20 1 n: ... 1 10
Note that the 20 appears twice, and that the “reference count” has increased from 1 to 2. That means that there are two references to the same number item. If you “drop” the TOS, you’ll see the reference count go back to 1.

There are a lot of stack manipulation words in 8th. Here are some of the most common used, along with their stack-effect diagrams:

  • dup — \ a -- a a
  • drop — \ a --
  • swap — \ a b -- b a
  • over — \ a b -- a b a
  • tuck — \ a b -- b a b
  • nip — \ a b -- b
  • rot — \ a b c -- b c a
  • -rot — \ a b c -- c a b
  • 2dup — \ a b -- a b a b
  • 2swap — \ a b c d -- c d a b

Exercises

Try the following. Before each exercise type reset 10 20 30 — note that “reset” clears the stack so you’re starting again with a clean slate. Check the stack using the .s word:

  • Make the stack look like: 10 30 20
  • Make the stack look like: 10 20 30 20 30
  • Make the stack look like: 20 30 10
  • Make the stack look like: 20 10 30
  • Make the stack look like: 20

Conclusion

You can now manipulate the order of items on the stack. This is a fundamental skill you’ll use over and over when programming in 8th.