Swap
A grid of stack commands where every command, once it has run, turns into its opposite.
splcurran, 2009 · Turing complete: unknown · ●●● hard · esolangs.org
Tested with 5 known programs · Hello World on Try It Online: identical · Test method
Run it
The idea
Swap looks like a small Befunge. An instruction pointer moves across a grid that wraps at its edges, and the cells push digits, do arithmetic and turn the pointer. The twist is in the name. Each command has a partner, < and >, + and -, o and i, s and x, and after a cell runs it is replaced by its partner. A loop therefore does something different on every other pass.
Read the story
This is the stack language TIO runs as Swap, from splcurran's repository. It is not the string rewriting language of the same name on esolangs.org.
The machine
Two stacks of unbounded integers, an empty stack popping 0. The pointer starts top left, moving right. This implementation follows splcurran's Python interpreter.
| Command | Does | Turns into |
|---|---|---|
> < ^ v | Move that way | < > v ^ |
/ \ | Mirrors | \ / |
\| _ | Turn round when moving across; along | _ \| |
[ ] | Point left; right | ] [ |
? ! | Pop, jump over the next cell when 0; when not 0 | ! ? |
" ' | String mode; push the next cell | ' " |
0-9 | Push the digit | |
i o | Read a character; print one | o i |
, . | Duplicate; drop | . , |
% $ | Switch stacks; swap the top two | $ % |
@ # | Top to the bottom; bottom to the top | # @ |
+ - * : | Add, subtract, multiply, floor divide | - + : * |
( ) = ~ | Less, greater, equal, not equal | ) ( ~ = |
s x | Nothing; end | x s |
In the interpreter, $ pops into the same variables that hold the pointer's position, so it also moves the pointer to the place the two values name. This implementation keeps that.
Example
In the second program s does nothing the first time and becomes x, so the pointer wraps round to an end.
In the second program s does nothing the first time and becomes x, so the pointer wraps round to an end.
Patterns it teaches
- Self-modifying code: every cell rewrites itself as it runs.
- Two-dimensional control flow: a Befunge-like grid.
- Stack machines: two stacks to work in.
Further
- The interpreter, in Python
See also
String-rewriting paradigm
Self-modifying
Write your own in Run Convert a program from Swap
Implementation
JavaScript interpreter, source and command line
A JavaScript interpreter, used in the browser and on the command line. Id: swap.
Command line
shib run swap -e 's"A"o'shib manual swapSource
- Module
langs/tio/ports.js- Interpreter
langs/tio/swap.js
Docs: Kernel instructions · The .shib format · Command line · Adding a language
Source esolangs.org (CC0) · Edit on esolangs.org