esolang

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

Expected: Hello, World!

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.

CommandDoesTurns into
> < ^ vMove 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-9Push the digit
i oRead a character; print oneo 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 xNothing; endx 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.
Expected: A
Expected: cba

In the second program s does nothing the first time and becomes x, so the pointer wraps round to an end.

Patterns it teaches

Further

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 swap

Source

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