-
Notifications
You must be signed in to change notification settings - Fork 1
Tutorial: The Stack
sclin is a stack-based language, meaning that computations in sclin are primarily centered around a stack. (Wow, how insightful!) Whereas in other languages, you might do:
(6 + 8) * 5
In sclin, you might instead do:
6 8 + 5 *
Here's what the stack goes through:
Token | Meaning | Stack |
---|---|---|
6 |
push 6 | 6 |
8 |
push 8 | 6 8 |
+ |
pop top 2 items, add, push result | 14 |
5 |
push 5 | 14 5 |
* |
pop top 2 items, multiply, push result | 70 |
The stack serves as a way to both return and store data.
On its own, the stack doesn't have much use. But stack combinators allow you to manipulate the stack, opening up a whole variety of options for stack-based computation. For example, let's say you wanted to write:
10 / (8 - 6)
In sclin, you could write:
10 8 6 - /
But you could also write:
8 6 - 10 swap /
Or if you wanted to get really unnecessarily fancy:
6 8 10 rev - /
The "elementary" stack combinators are dup
(a -> a a
), pop
(a ->
), swap
(a b -> b a
), rot
(a b c -> b c a
), and rot_
(a b c -> c a b
).
Here are the combinators, arranged by variations:
Elementary | Alters top items | Alters entire stack | Alters based on index |
---|---|---|---|
dup |
dupd over ddup edup
|
dups |
pick |
pop |
nip ppop qpop
|
clr |
nix |
swap |
swapd tuck
|
rev |
trade |
rot |
roll |
||
rot_ |
roll_ |
Stack combinators are comparable to combinators found in functional programming
languages. For example, flip
in Haskell:
flip f x y = f y x
flip (-) 5 1 -- => -4
Is the same as 5 1 swap -
in sclin.
Made with ❤️ by Ben Pang (@molarmanful).