Write some amount of documentation
This commit is contained in:
118
docs/stack.md
Normal file
118
docs/stack.md
Normal file
@@ -0,0 +1,118 @@
|
||||
# The Stack
|
||||
|
||||
Forth is a stack-based language. Instead of variables and expressions, you push values onto a stack and use words that consume and produce values.
|
||||
|
||||
## How It Works
|
||||
|
||||
The stack is a last-in, first-out (LIFO) structure. Values you type get pushed on top. Words pop values off and push results back.
|
||||
|
||||
```
|
||||
3 4 +
|
||||
```
|
||||
|
||||
Step by step:
|
||||
1. `3` → push 3 onto stack: `[3]`
|
||||
2. `4` → push 4 onto stack: `[3, 4]`
|
||||
3. `+` → pop two values, add them, push result: `[7]`
|
||||
|
||||
## Values
|
||||
|
||||
Three types can live on the stack:
|
||||
|
||||
- **Integers**: `42`, `-7`, `0`
|
||||
- **Floats**: `3.14`, `0.5`, `-1.0`
|
||||
- **Strings**: `"kick"`, `"hello"`
|
||||
|
||||
## Stack Notation
|
||||
|
||||
Documentation uses stack effect notation:
|
||||
|
||||
```
|
||||
( before -- after )
|
||||
```
|
||||
|
||||
For example, `+` has effect `( a b -- sum )` meaning it takes two values and leaves one.
|
||||
|
||||
## Core Words
|
||||
|
||||
### dup
|
||||
|
||||
Duplicate the top value.
|
||||
|
||||
```
|
||||
3 dup ( 3 3 )
|
||||
```
|
||||
|
||||
### drop
|
||||
|
||||
Discard the top value.
|
||||
|
||||
```
|
||||
3 4 drop ( 3 )
|
||||
```
|
||||
|
||||
### swap
|
||||
|
||||
Swap the top two values.
|
||||
|
||||
```
|
||||
3 4 swap ( 4 3 )
|
||||
```
|
||||
|
||||
### over
|
||||
|
||||
Copy the second value to the top.
|
||||
|
||||
```
|
||||
3 4 over ( 3 4 3 )
|
||||
```
|
||||
|
||||
### rot
|
||||
|
||||
Rotate the top three values.
|
||||
|
||||
```
|
||||
1 2 3 rot ( 2 3 1 )
|
||||
```
|
||||
|
||||
### nip
|
||||
|
||||
Drop the second value.
|
||||
|
||||
```
|
||||
3 4 nip ( 4 )
|
||||
```
|
||||
|
||||
### tuck
|
||||
|
||||
Copy top value below second.
|
||||
|
||||
```
|
||||
3 4 tuck ( 4 3 4 )
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
Build a chord by duplicating and adding:
|
||||
|
||||
```
|
||||
60 dup 4 + swap 7 + ( 64 67 60 )
|
||||
```
|
||||
|
||||
Use `over` to keep a base value:
|
||||
|
||||
```
|
||||
c4 over M3 swap P5 ( e4 g4 c4 )
|
||||
```
|
||||
|
||||
## Words
|
||||
|
||||
| Word | Stack | Description |
|
||||
|------|-------|-------------|
|
||||
| `dup` | (a -- a a) | Duplicate top |
|
||||
| `drop` | (a --) | Discard top |
|
||||
| `swap` | (a b -- b a) | Swap top two |
|
||||
| `over` | (a b -- a b a) | Copy second to top |
|
||||
| `rot` | (a b c -- b c a) | Rotate three |
|
||||
| `nip` | (a b -- b) | Drop second |
|
||||
| `tuck` | (a b -- b a b) | Copy top below second |
|
||||
Reference in New Issue
Block a user