Stack Words II
Here are a few more useful built-in words for the stack:
Word | Action |
---|---|
.S |
Displays the number and contents of the stack without altering it. |
OVER |
1 2 OVER .Sbecomes <3> 1 2 1 |
NIP |
1 2 NIP .Sbecomes <1> 2 |
TUCK |
1 2 TUCK .Sbecomes <3> 2 1 2 |
DEPTH |
Puts the number of items on the stack. For example, "Hello" "Smojo" DEPTH .Sbecomes <3> "Hello" "Smojo" 2 |
The Return Stack
In addition to the main stack, Smojo also has a "return" stack. This is often used for temporary storage of items. Some words:
Word | Action |
---|---|
.R |
Displays the number and contents of the return stack without altering it. |
>R |
Pops the top of the stack and pushes it onto the return stack. |
R> |
Pops the top of the return stack and pushes it onto the main stack. |
R@ |
Pushes the top of the return stack (without popping it) onto the main stack. |
RDROP |
Drops an item from the top of the return stack. |
>R,
R>,
R@and
RDROP.
Quiz
Question 1
Rewrite the advanced stack words:
NIP,
OVER,
TUCK,
R@and
RDROPin terms of the basic stack and return stack words.
: NIP swap drop ; : OVER >R dup R> swap ; : TUCK swap >R dup R> swap ; : R@ R> dup >R ; : RDROP R> drop ;
Question 2
Consider the wordROT("rotate") that behaves this way:
1 2 3 ROTbecomes
2 3 1
Write this word in terms of the words you know.
Question 3
Consider the word-ROT"undoes"
ROT:
2 3 1 -ROTbecomes
1 2 3
Write this word in terms of the words you know.
: rot >R swap R> swap ; : -rot swap >R swap R> ; 1 2 3 rot .s \ 2 3 1 -rot .s \ 1 2 3
Question 4
Write the words{{and
}}that counts the number of items between them, without altering the stack. For example:
{{ 1 2 "mini" 3 }}becomes
1 2 "mini" 3 4
: {{ depth >R ; : }} depth R> - ;