A stack is a data structure often used as an esoteric programming language's memory. The number of stacks may vary. Many languages have other methods of data storing as well.
A stack works by the principle of Last In, First Out (LIFO). What is pushed onto the stack first, will be popped off last. This leads to the two primary stack operations: PUSH, which adds something to the top of the stack, and POP, which removes something from the top and returns it. Oftentimes, popping an empty stack causes an error or returns zero.
In addition to PUSH and POP, there are a few other stack manipulation operations that stacks can use that are generally accomplished through scalar variables.
The following table lists them, including the operation, its name, its traditional (or completely made up) laconic representation, its meaning, and an example in "Generic Stack Language" (GSL), a language used solely for example purposes.
||Peek||Return the top of the stack without removing it.|| |
||Drop||Remove the top item of the stack and discard it|| |
||Duplicate||Duplicate the value on the top of the stack.|| |
||Swap||Swap the positions of the top two values on the stack.|| |
||Over||Put the second item on the stack on the top of the stack WITHOUT removing it from its original location.|| |
||Rotate||Rotate the top three items on the stack clockwise.|| |
||Rotate Counterclockwise (anticlockwise)||Rotate the top three items on the stack counterclockwise.|| |
- Main article: Postfix notation
A stack can be used to very easily evaluate expressions written in postfix notation. Simply go through the values on the list, and if it's a number, push it. If it's a unary operator, pop a value, call that operation on it, then push the new value. If it's a binary operator _, evaluate GSL
POP→a; POP→b; PUSH b_a. If it has any higher arity, just pop the desired number of arguments from the stack and insert them into the expression in reverse order.
Usage in esolangs
Here are some examples of esoteric programming languages using stacks:
- Befunge uses one stack, which is not the only way to store data (the other is to make the program modify its own source, stored in the memory of the interpreter during execution).
- False uses a stack for parameters and a return stack for function calls, like Forth.
- TLWNN uses two stacks, and that's its only way to store data.
- Kipple uses many stacks, and that's its only way to store data.
- Stacking uses two stacks, as well as a memory pool.
- Super Stack! uses a single stack for data storage.
- Vitsy uses a two-dimensional program stack and a one-dimensional input stack.
It can be shown that two (unbounded) stacks are equivalent to an unbounded memory tape and therefore that a programming language with at least two stacks is Turing-complete, provided it has a suitable semantics for manipulating stack values.