• This thread is open and unlocked only because the community decided to make an exception. Please do not use this question as evidence that you can ask similar questions here. Please do not create additional questions.

  • This is no longer a , nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.

This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.

How this works

  • All answers should include the name of the programming language at the top of the post, prefixed by a #.

  • Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.

  • Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.

  • The snippets do not need to be related. In fact, snippets that are too related may be redundant.

  • Since this is not a contest, all programming languages are welcome, whenever they were created.

  • Answers that contain more than a handful of code snippets should use a Stack Snippet to collapse everything except the factoid and one of the snippets.

  • Whenever possible, there should be only one answer per programming language. This is a community wiki, so feel free to add snippets to any answer, even if you haven't created it yourself. There is a Stack Snippet for compressing posts, which should mitigate the effect of the 30,000 character limit.

Answers that predate these guidelines should be edited. Please help updating them as needed.

Current answers, sorted alphabetically by language name

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/44680/answers?site=codegolf&filter=withbody",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('<li><a href="/a/' + data.items[i].answer_id + '">' + temp.innerText || temp.textContent + '</a>');}}})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><base href="http://codegolf.stackexchange.com"><ul id="list"></ul>


237 Answers 237

1 2
4 5


Go, also commonly referred to as golang, is a programming language initially developed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed language with syntax loosely derived from that of C, adding garbage collection, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library.

Link for myself, or anyone who wants to contribute to this answer.

Length 14

var x [9]int32

This is an example of how to create an fixed array. You can access it use normal indexing operation x[8] for example. You can iterate any array or slice using for-range statement, for example:

for index, value := range x { // value == x[index]
for index := range x {
for _, value := range x {

Length 13

var x []int32

This is a longer example of slice, slice is a struct that stores current length, capacity and pointer to an array. to get the capacity you can use cap(x), to get the current length of the slice, you can use len(x) function. To add an element to the last element you can use x = append(x,data) function, if capacity equal to the current length, it will copied to another array, and the slice points to that new array.

Length 12

var x *int32

This is an example of pointer variable, a pointer most useful to change a value that declared outside function, for example:

func SquareIt(n *int32) {
  v := *n
  *n = v * v

This function would multiply a variable passed into it (you must prefix with & when passing non-pointer into pointers), for example:

y := int32(12)
fmt.Println(y) // 144

A pointer also can be used to change function owner's member, for example:

type Person struct {
   Age int
func (p Person) Aging1() { p.Age += 1 } // doesn't change the age
func (p *Person) Aging2() { p.Age += 1 } // change the age
func main() {
  me := Person{Age:28}
  fmt.Println(me.Age) // 28
  fmt.Println(me.Age) // 29

Length 11


This is an example of a type that can hold anything. The interface{} translates to "any type that implements at minimum 0 function". Here's better use-case on how to use this keyword

type Stringer interface {
  String() string

That snippet above means that Stringer is a type that could hold anything that already implements String() string function (function named String that returns a string), for example:

type Hooman struct {
  Name string
  Age int
func (h Hooman) String() string {
  return "I'm a hooman named " + h.Name + " " + strconv.Itoa(h.Age)
func main() {
  me := Hooman{}
  me.Name = "kis"
  me.Age = 28
  x := Stringer(me)
  fmt.Println(x.String()) // kis 28

Length 10

func X(){}

This is an example of how to create a function. This function named X that holds zero parameter and doesn't return anything. You can add parameters/arguments between the () and return type between the ){, for example:

func Add(a int, b int) int {
  return a + b

Or alternative syntax:

func Add(a, b int) (c int) {
  c = a + b

A function can have its own owner, this function often called method in another language, to set the ownership of a function, just type the owner between func and the function name, for example

type Person struct {
  Name string
  Age  int
func (p Person) Print() {
  fmt.Println("I'm a person named " + p.Name)
func main() {
  me := Person{"kis",28}

Length 9

package X

This is an example of the first statement that you must type to create a package/library. The library would be called X, all function, type, constants or variables that declared capitalized, can be accessed from another package by typing X.The_name_of_the_function_or_type_or_constants_or_variables after including the package folder using import keyword. Normally the folder name is equal to the package name, visit here for more information about code organization.

Length 8


This is an example on how to create a slice that points to an array that contains an element with value 3. To increase the slice you may want to use append function, for example: x := []int{3}; x = append(x,7), now that slice will point to an array that have a value of 3 and 7, that equals to []int{3,7}, to get the length of that slice, use len function, to get the capacity of underlying array, use cap function.

Length 7


This is the name of standard library that useful to convert mostly anything from/to a string, for example:

package main
import `strconv`
import `fmt`
func main() {
  fmt.Println(strconv.Itoa(1234) + ` is a string now`)

Length 6


Struct is a keyword to create a record or a new data structure, that compose another type, this is an example of how to create a new type called Person

type Person struct {
  Name string
  Age  int

Length 5


This is an example of slice data type, slice is a struct that have pointer to real array, a current length of the slice and capacity of that array. Slice is just like a microscope that shows only a part or whole of original array.

Length 4


This is an example for a shortcut to create a variable named x and initialize it with int value of 3. The longer version to do the same thing is: var x int = 3. There's no need to add semicolon at the end of each statement.

Length 3


This is an example on how to create a float constant with float32 or float64 depends on the context.

Length 2


Backquote is the string literal, inside those quote could be almost anything (including newline) except the backquote itself.

Length 1


This is the example of number literal, this number could be anything, rune (character), uint8 or byte, int8, uint16, int16, uint32, int32, uint, int, uint64 int64, float32, float64 depends on the context, the default is int.


Gopher (the mascot of go programming language) is a real animal (rodents family).



Labyrinth is my new two-dimensional programming language. I'm unreasonably proud of how it turned out, so I figured this would be a good place to introduce it and maybe popularise it a bit.


Labyrinth is a 2D stack-based language without any control flow commands. Instead, control flow is determined by the layout of the source code, which is supposed to resemble a maze (hence the name).

Length 1 snippet


Every command in Labyrinth is a single character and occupies a "cell" in the 2D source code. Let's start with the latest addition to the language, because it's useful during programming and because it let's me get some basics out of the way.

The command ' is normally just a no-op, but when the interpreter is invoked with -d (debug mode), ' prints debug information about the current state. This information includes the grid (i.e. the source code; we'll see later why this is useful), the position of the IP, the moving direction of the IP, as well as the stacks. This is all the state there is in Labyrinth.

What stacks? Labyrinth operates on two stacks, "main" and "auxiliary". They both initially hold an infinite amount of zeroes, and can hold arbitrary signed integers. I picture them with the tops facing each other, growing towards the centre, i.e.:

Main [ ... 0 0 1 3  |  -123 345 1 0 0 ... ] Auxiliary

where ... represents the infinite amount of zeroes at the bottom. This is also how they are printed by ' and how some operator symbols have been chosen.

One last detail: Labyrinth doesn't terminate unless the IP hits a specific command. In a 1-cell program, the IP will instead repeatedly execute that one cell. This means the above program is simply an infinite loop that never prints anything. If we switch on debug mode, the code will instead repeatedly print

Position: (0,0)
Direction: East
Main [   |   ] Auxiliary

Note that both stacks are currently empty (the infinite amount zeroes is, of course, not printed but implied).

Length 2 snippet


What's this? I don't know yet. [ and ] are the only two non-letter characters which don't have an assigned function yet (and letters won't get any). So currently these are "walls" just like spaces and letters. A program which consists only of walls is considered empty and terminates immediately.

But: I am planning to add commands for these two characters eventually, and this snippet serves as a placeholder until then. I'm happy to receive suggestions what these two characters should do! If you have an idea let me know in The Nineteenth Byte or the dedicated Labyrinth chat room.

Length 3 snippet

Okay, real code now...


Let's take a nap... this code prints an infinite stream of ZZZZZZZ.... There are two things of note here:

First, in languages where each character is a separate command you can often only push numbers in the range 0..9 and have to build larger numbers with arithmetic. This can get annoying, so in Labyrinth instead, a digit will multiply the top of the stack by 10 and then add itself. This lets you write out numbers in decimal in the code. Emmental has this feature as well. So 90 will actually create a 90 on the stack for . to print as the character Z.

Second, as opposed to many other 2D languages, the edges of Labyrinth's source code don't wrap around. So the IP hits a dead end after executing .. When this happens, the IP simply turns around and continues in the opposite direction. So the IP keeps bouncing back and forth in the source code, executing

and so on, repeatedly printing Z.

Length 4 snippet


Printing is important, so Labyrinth comes with two more commands in addition to .. ! prints the integer value in decimal (as opposed to treating it as a character code). Note that it doesn't print a newline. But printing newlines is quite a common task, and having to do _10. each time is annoying, so there's \ which just prints a single newline.

I'm also introducing @ here. This terminates the program, so we don't have to keep writing infinitely-looping code. So this snippet happens to print its length 4, a newline and then exits cleanly.

Length 5 snippet

I think we can spare a newline now:


? is the input-equivalent of !: it reads as many bytes from STDIN as it can to form a valid (signed) integer and pushes it onto the main stack.

Now the IP can't move to the right, because there's a wall there (spaces and letters except v are walls; the source code is implicitly padded to a rectangular area with spaces). However, the IP can move down so that's what it does. This is essentially the dead-end rule from snippet 3: if there is only one non-wall neighbour, move there. (From now on "neighbour" will always imply "non-wall neighbour").

~ computes the binary NOT of the top of the stack. The IP hits another wall. However, this time it's not a dead end. It doesn't have to turn around, but it can take a left turn, so that's what it does instead. ! prints the newly computed value, @ ends the program.

This turning behaviour is important, so here are the exact rules for when the current cell has exactly two neighbours:

  • If the IP can keep moving straight ahead, it does.
  • Otherwise, the IP moves such that it doesn't reverse direction.

These two rules allow the IP to follow any "corridors" of code, even around bends. There is one more subtle special case for two neighbours, but we'll get to that later.

Length 6 snippet


Our first real program. Those 6 bytes implement cat. , is to ? what . is to !: it reads a single byte from STDIN and pushes its value onto the stack. When we hit EOF, it pushes -1 instead. I have borrowed ( and ) from CJam: they decrement and increment the top of the stack respectively.

But the most important thing about this snippet is what happens after the read byte has been incremented by ). This time, the current cell has three neighbours: the one we came from, one straight ahead (the @) and one which requires a right-turn (the (). So where do we go?

For these kinds of junctions (3 or 4 neighbours), the top of the main stack is examined (but not popped). If it's zero, the IP continues moving straight ahead. If the top value is negative, it takes a left-turn. If it's positive, it takes a right-turn. In the case of 3 neighbours, any of those decisions might hit a wall: in that case the opposite direction is picked. This little mechanic is the way to implement control flow in Labyrinth.

And what happens in this specific case? As long as we're reading bytes (which will be 0 or greater), the ) increments the value to a positive number so we take a right turn. ( decrements it back to its original value before it's printed with . and we move on to reading the next byte. At EOF, the ) will increment the -1 to 0, so the IP moves straight ahead, leaves the loop, hits the @ and terminates the program. Nifty, isn't it? :)

Length 7 snippet


We've seen in 3 how we can write simple endless loops, but the problem is the IP bounces back and forth. Not every code can easily be written such that it will still do the right thing if ran as a palindrome. Can we write similarly simple (i.e. linear) loops which just run each command once per iteration, but still put them on a single line?

For that, let me give you a glimpse at Labyrinth's second major feature (the first being how control flow works). It has four commands <, >, ^, v which can modify the source code at runtime. Each of them pops one value from the main stack and then rotates (i.e. shifts cyclically) a particular row or column of the grid by a single cell. If the IP is on the row or column that is being shifted, it moves with the shift, potentially through the edges of the grid. This shift does not affect the IP's current orientation, and the IP will still make its normal move afterwards. I'm not aware of any other language where source code manipulation works like this.

So let's look at this code again. We start on <, which pops a 0 from main. The 0 indicates that the IP's own row is being shifted (to the left). So we get this code:


But the IP is now at the right end of the grid. It can only move left so it does. Next it hits >, which shifts the source code back in place:


The IP is still at the right end, moving left. Now it executes the actual content of the loop, 32,$.: push a 32, read a byte, bitwise XOR, write the byte.

What does this do? If the program receives a stream of letters on STDIN, it will change the case of each letter and print them to STDOUT. E.g. abCdE turns into ABcDe. If we reach EOF on STDIN the program will terminate with an error, but let's not worry about that.

I will try to show some more elaborate use of the grid rotation commands in later snippets.

Length 8 snippet


You should actually consider this one a snippet, not a full program. Assume that the IP enters this from the top and will leave to the right. Let's see what it does:

As mentioned in the first snippet, " is a no-op. It can be used to lay out paths of the Labyrinth without affecting the stacks.

: duplicates the top of the main stack. If that value is non-zero, the IP will take a left-turn towards the -, which subtracts the two values. Since they are both the same, this gives zero and the IP leaves the snippet to the right.

If the duplicated value is zero instead, the IP moves further down. ~ takes the bitwise NOT, turning 0 into -1. The IP then follows the bend through the no-op, onto the -. Now this computes 0 - (-1), i.e. 1. The top of the stack is now positive and the IP takes a right-turn and leaves the snippet in the same direction as before.

In summary, this turns non-zero values into 0, and zeroes into 1. It is therefore a very compact implementation of logical NOT.

Length 9 snippet


Again, consider this a snippet. The IP enters it from either the left or the top.

A well-known problem in 2D languages is the wire-crossing problem. While Labyrinth doesn't need wire-crossing (or source manipulation) to be Turing complete, being able to cross paths of the Labyrinth can be very helpful when laying out the code.

There are several ways to cross "wires" in Labyrinth, and this snippet is the simplest one. _ pushes a zero onto the main stack (this command is also necessary to push new numbers on the stack, because all the digits, including 0 just change the value of the to of the stack). So no matter whether the IP enters from the left or the top, the main stack will hold a 0 when the IP reaches the intersection. This means the IP will travel straight ahead. ; discards the top of the main stack, in order to return to the previous state.

Length 10 snippet


Consider this a snippet, but be aware that the height of the full source code should not be greater than three lines. The snippet is entered at the top left (on the _, going east) and exited either at the top right or bottom right (going east). The snippet also assumes that there's a 0 on top of the main stack.

I mentioned in snippet 5 that there's one more case to be considered for control flow when the current cell has two neighbours. Let's see what happens here:

The _ pushes another zero onto the stack. Now the stack rotation v pops that zero and shifts the current column down by one, taking the IP with it:


Now the IP is still facing east, and the current cell has two neighbours, above and below. This means the IP can neither move straight ahead, nor could it reverse its direction, so in principle both choices are valid. If the top of the main stack was non-zero, we'd apply the same rules as for three or four neighbours: for a negative value turn left (north), for a positive value turn right (south). But the top of the main stack is zero. In this particular case, the direction is chosen randomly (choosing uniformly between the two options). This is Labyrinth's built-in PRNG. It's quite tricky to use, because the required conditions on the IP can only be set up with the grid rotation commands, and it only makes a binary decision, but it can be used to build up larger random numbers with some effort.

Now that the IP has chosen a random direction, what happens next? If it goes up, the zero on the stack is incremented to 1 and the IP takes a right turn and leaves the snippet at the top. If the IP went down instead, the zero remains unchanged and the IP leaves the snippet at the bottom. So this snippet can be used to either a) just generate a random bit on the stack or b) choose one of two execution paths at random (or both).

  • 1
    \$\begingroup\$ The use of digits as operators that also work for creating multi-digit numbers is incredibly smart! I'll keep that in mind when designing future esolangs. +1 'cause I'd like to see more. :) \$\endgroup\$ Sep 5 '15 at 19:33
  • \$\begingroup\$ I'm gonna have to learn this language, it looks like it'd be fun to golf in. +1 because I'd like to see what it can really do. \$\endgroup\$ Sep 22 '15 at 19:08
  • \$\begingroup\$ I have some ideas for [ and ]. They could be used for bit-shifting. They could be used for some sort of crazy goto (maybe one pops twice and goes to those coordinates on the grid, and maybe the other goes to 0,0 always). You could change all of the arithmetic to be floating point and [,] could be floor and ceiling. Just some ideas. I love the language, btw! \$\endgroup\$ Nov 7 '16 at 15:51


Factoid: Plurp is a two-dimensional programming language closely related to
><> (fish) and Befunge. It is inspired by ><>.

1 character


An infinite loop. Like in ><> and Befunge, code will wrap around in Plurp.

In fact, any command but ; when by itself in a program would result in an infinite loop.

2 characters


Outputs 1 indefinitely. Any number from 0 to 9 would do pretty much the same.

3 characters


Finally! Something interesting! This is a cat program which outputs its input.

4 characters


Demonstrates the pop (~) function. Although this pushes 1 to the stack, it is popped and therefore the program outputs nothing.

5 characters


Prints a. This demonstrates the string parsing function: when an ' is encountered, the rest of the characters are pushed to the stack as character codes until another ' is encountered. This leads to the escape for ' being quite costly: '39&'

The & used in '39&' concatenates the top two numbers on the stack (39 is [3, 9] but 39& is [39]).

6 characters


Demonstrates the right-shift function. 1, 2, and 3 are pushed onto the stack, then the stack is shifted right (by one position). The output of this program is "312", as the 3 wraps around.

| can also be replaced with \ (the left-shift operator) to shift the stack one position left instead of right. This has a surprising number of applications in Plurp.

7 characters


Like ><>, Plurp can create multiple stacks and run operations on each stack independent of the others.

There are three different kinds of stacks - additive [, overlap (, and copy additive {. Stacks are classified by their behaviours when opened and closed with ] or flattened with f.

Additive stacks will be empty when open ([]) and will add their data to the end of the next stack when closed. 4[2]i; outputs 42.

Overlap stacks will be empty when open and will add their data to the beginning of the next stack when closed. 4(2]i; outputs 2.

Copy additive stacks are like additive stacks, but they open with the data of the last stack already in them. 4{2+]i; outputs 442.

8 characters


Like ><>, Plurp has a register (albeit only a single one). When a " is encountered, the interpreter checks if the register is empty. If it is, the top value on the stack is popped and pushed into the register. Otherwise, the value in the register is popped and pushed into the stack.

Therefore, even though there are two i commands, only one outputs 42 because the other is called while 42 is in the register and not the stack.

9 characters


A quine! From all the above snippets, you have enough information to figure out how this works. The key is that string parsing wraps around in this programming language, much like all regular commands.

Read Me

Currently the interpreter is broken due to the addition of an infinite-loop prevention system in Khan Academy. I'm working to fix it, and once I do I will catch up with this answer!

  • \$\begingroup\$ Why is this so popular!? \$\endgroup\$ Jul 1 '15 at 13:53
  • 1
    \$\begingroup\$ Are you thinking of names yet? \$\endgroup\$
    – mbomb007
    Sep 4 '15 at 22:03
  • \$\begingroup\$ No, I really need to add more programs though. \$\endgroup\$ Oct 16 '15 at 2:13
  • \$\begingroup\$ le bump please add programs* \$\endgroup\$ Jul 26 '16 at 0:48
  • \$\begingroup\$ Hi! I've finally gotten around to re-making a working interpreter. I will be adding programs soon! \$\endgroup\$ Feb 5 '17 at 16:12


The programming language that everybody grew up on[citation needed]--at least, everyone who grew up with MS-DOS during the 90s.


QBasic is actually an interpreter and an IDE together. When you enter code, the QBasic editor automatically formats it for things like whitespace and capitalization. The QB64 emulator, which I'm using to test my programs, gives the option of turning auto-formatting off, allowing a few nice golfing shortcuts in an otherwise fairly verbose language.

Length 1


This is a valid QBasic program--but only because QBasic allows line numbers. The above is therefore an empty statement (on line number 1), which does nothing.

Length 2


Lots of stuff going on here:

  • ? is a shortcut for PRINT.
  • a is a variable. Since it doesn't have a type suffix and hasn't been declared with DIM, it is numeric; so it is auto-initialized to 0.
  • Thus, this program is basically equivalent to PRINT 0. But because QBasic is optimized (?) for outputting numeric data in tables, what it actually prints is 0 . (The leading space is so 1 and -1 will line up properly, and I suspect the trailing space is so that printing multiple numbers in a row won't result in something like -1-2-3.)

Length 3


QBasic doesn't use an output stream like C-based languages; instead, it uses a cursor to write stuff to a window (see snippet 13 for more on that). The DOS implementation doesn't clear the window between runs, so it can start to get cluttered after a while:


--which is why most QBasic programs have the CLear Screen command somewhere near the beginning.

(The QB64 emulator starts over with a blank screen each time you run your program, which I find just a little disappointing.)

Length 4


Does just what you think it does.

What I like about QBasic is that it has fun commands like this built into the syntax, whereas other languages usually require external libraries or weird workarounds. In Python, for example, the quickest way to get a beep is the extremely cryptic print("\a"); but that doesn't even work in all environments (in particular, the IDLE shell that comes with Python prints a bullet character instead).

Length 5


^ is exponentiation, of course. (Don't know what possessed C and its derivatives to use it for bitwise xor.)

Despite the fact that this looks like integer math, we don't get an overflow. The default numeric type in QBasic is actually SINGLE, which is a floating-point number that shows (up to) seven significant digits. If the fractional part is zero, it will display as an integer: for example, PRINT 1.0 outputs 1. The result above has more than seven significant digits, however; so we get it in scientific notation as 4.398047E+12.

Annotating one of the operands with the # suffix would coerce the expression to DOUBLE precision, giving up to fifteen significant digits: ?2#^42 gives 4398046511104.

Length 6


Our first multi-statement program! : is a statement separator.

The RUN command can be used in a few different ways. If you give it the name of another QBasic source file, it will switch execution to that program. If you give it a line number in the current program, it will restart the program at that line. (This is different from a GOTO because all variables are cleared, as if starting the program from scratch.) And if you don't specify an argument, it will restart the program from the top. The code above prints 1 infinitely.

If you don't want the 1s on their own lines, you could use ?1;:RUN--the semicolon suppresses the newline when printing. But that will actually give you 1 1 1 ... (see the length-2 snippet for why). To fill the screen with 1s, you'd need to use a string: ?"1";:RUN.

Length 7


The INPUT statement by default displays a ? prompt and waits for the user to enter a value. Lacking a type suffix, x is a single-precision numeric variable, so anything like 3.14 or -42 is valid input. What happens if you try to enter something that's not a number?

? Jabberwocky
Redo from start

It's a bit cryptic, and it can royally mess up the alignment if your program is using some kind of text-based user interface, but at least the program doesn't crash, interpret the input as 0, or anything weird like that. ;^)

Note: QB64 doesn't even let you type invalid characters when an INPUT statement asks for a number.

Length 8


Music is yet another feature awesomely built in to QBasic. This code plays two quarter notes (middle C and middle F). A PLAY string has ways of changing the octave, playing sharps and flats, changing the duration of notes, and so much more!

Length 9


Different SCREEN modes in QBasic allow for different graphical capabilities: various resolutions, color vs. black-and-white, text-only or graphics-capable. Historically, these were included to account for differences among display hardware. The default mode, SCREEN 0, is text-only, so any program with graphics in it has to start with a SCREEN statement. (Pretty pictures later if I get more votes!)

Length 10


Would you care for some pi? QBasic has a good number of math functions built in, ArcTaNgent among them. The # type annotation is used here to make the resulting value DOUBLE, so we get more digits: 3.141592653589793.

Length 11

COLOR 2:?42

Time to get colorful.

Green 42 (Shown 2x actual size)

In the default SCREEN 0, QBasic offers 16 foreground colors:

The 16 colors in QBasic

Each color 8-15 is a lighter version of the corresponding 0-7 color. The darker colors 0-7 are also available as background colors, and adding 16 to a foreground color makes it blink! (See this thread, particularly the bottom post, for a great historical explanation.) So, since a COLOR statement affects everything subsequently printed, we can write this:

COLOR 25,4

and see this:

Blinking "Press any key"


Length 12


The DRAW command takes a string of codes and draws stuff on the screen. As a graphics command, it cannot be used in the default screen mode, so you'll need to combine this snippet with snippet 9 in order to run it. This example goes 3 pixels diagonally down and right, 7 pixels up, and 9 pixels right, for a tiny square root symbol:

QBasic DRAW command--square root symbol (Shown 2x actual size)

Length 13

LOCATE 7,8:?9

Recall (from snippet 3) that QBasic outputs text to a window, not an output stream. The LOCATE command allows you to set the cursor location for output. So if you want to display something halfway down the screen, you don't need to print a bunch of newlines first--just LOCATE to the right row and column.

Using LOCATE command

Importantly, this doesn't affect any other text on the screen (except when directly overwriting it), which makes QBasic very straightforward for creating textual user interfaces--or dungeon games. Most languages would have to use control codes or a library like curses.

Length 14


What would QBasic be without GOTO? The much-maligned feature is alive and well here, allowing arbitrary jumps in program flow to defined labels. The above snippet, of course, skips to the third line and outputs 2.

A label must come at the beginning of a line. It can be any identifier followed by a colon; or, it can be a BASIC-style line number, sans colon.

While it is true that 1) most uses of GOTO can be replaced by conditionals or looping constructs and 2) those that are too complicated for this treatment are probably a bad idea to begin with, I still like GOTO, for a couple of reasons. First, it's how assembly works under the hood, so learning it first in QBasic is valuable practice. Second, I still think it's more readable (and less redundant) to write code like this:

IF x = 0 THEN PRINT "Enter a nonzero number": GOTO getNumber
PRINT "The inverse is"; 1/x

than the Python equivalent:

x = float(input())
while x == 0:
    print("Enter a nonzero number")
    x = float(input())
print("The inverse is", 1/x)

Length 15


QBasic does (pseudo)random numbers via the RND function, which is normally invoked without arguments and returns a random number in the range [0, 1). However, you'll get the same sequence on each run of the program unless you seed the PRNG with the RANDOMIZE statement. The usual seed is TIMER, which returns the number of seconds since midnight. This provides a different seed on each run of the program... at least, if you don't run it at exactly the same time each day.

If you do want the same numbers each run (maybe for testing purposes), you can pass a constant to RANDOMIZE--or just put RANDOMIZE without specifying a seed, in which case you'll be prompted when you run your program:

Random-number seed (-32768 to 32767)? 

Nobody can say QBasic isn't user-friendly.

Length 16


Graphics command: combine with snippet 9 to run.

QBasic's drawing commands are interesting because they each have a unique syntax, tailored to make the most sense for the particular command. The syntax for CIRCLE is CIRCLE (x, y), radius[, options]. (If you think that's odd, just wait till we get to see LINE in snippet 18.)

The first option to CIRCLE is color: we could have drawn a green circle with CIRCLE(9,9),8,2. But we've got an extra character to play with, so let's leave the color option blank (defaulting to white) and look at the next option. This happens to be startRadian. A value of 2 means that instead of a full circle, we get an arc of 2π - 2 radians:

Arc of circle (Shown 2x actual size)

(Note that this apparently follows the standard quadrants system, despite the fact that QBasic has the origin at the top left with the positive y-axis pointing down.) The remaining CIRCLE options are endRadian and aspect, which allows you to draw ellipses:


Half-squashed circle

Length 17


Reads an arbitrary line of text from the user and echoes it back.

What's important here is the word "arbitrary." The reason for the existence of LINE INPUT is that the regular INPUT command can't read commas. It treats them as field separators, so you can get two strings in one go by doing INPUT a$, b$. (Also useful for reading comma-separated data from a file.) But what if your input contains commas? Well, you can wrap it in double quotes and it'll treat the comma as part of the string. But what if your input also contains double quotes? That's when you need LINE INPUT, which simply reads everything until you hit enter.

Length 18


Graphics command: combine with snippet 9 to run. Draws a line from (1,1) to (9,9), right? Well... not exactly.

It's a box! (Shown 2x actual size)

This would create a diagonal line, except that we've also specified the B option for "box." So instead of a line, we get a rectangle. There's also BF for "box, filled." (As in snippet 16, the empty space between commas is for the unused color argument.)

I'm actually a fan of this unusual syntax, whenever it makes sense for the given command. I find that it's a mnemonic aid. Contrast the above with a function that takes a gajillion* positional arguments--you can never remember which one is which--or half a gajillion keyword arguments--you 1) have to remember the names of the keywords and 2) can end up with a pretty long line of code if you use multiple arguments. (I know the counterarguments; I'm just saying that this is something I enjoy about QBasic.)

* Slight hyperbole.

Length 19


Graphics command: combine with snippet 9 to run.

PAINT takes a starting point, a fill color, and a border color. It does a flood fill until it hits border-colored pixels or the edge of the screen. It's typically used to fill circles, rectangles, and other graphics figures. But hey, printed text is just pixels on the screen too:

0 donut filled with blue(berry) jelly (Shown 2x actual size)

Length 20


INPUT and LINE INPUT aren't the only ways to get input in QBasic. The INPUT$(n) function reads n keypresses and returns them as a string. (It can also be used to read from a file or a serial port.) INPUT$ does not display a prompt or echo the characters to the screen as they are typed. It therefore has a myriad of uses, from password entry to the famous "Press any key to continue."

The above program waits until the user presses a key, prints the ASCII code of that character, and loops infinitely using RUN (see snippet 6). Entering ABC123<esc><cr><tab><bksp> will result in output of

 65  66  67  49  50  51  27  13  9  8 
  • 1
    \$\begingroup\$ I know this is old, but I gave you the 13th upvote, and I'm interested in seeing what you can do with 13 characters (you mentioned it in your length 3 snippet). I grew up on QB45 and absolutely loved it. \$\endgroup\$ Mar 31 '16 at 19:28


MarioLANG is a two-dimensional programming language based on Super Mario. The source code's layout is similar to a Super Mario world, however the programs written in MarioLANG when compiled looks completely like a normal application, it is even turing complete!

Length 3 Snippet


Mario (our parser) starts in the upper-left corner, then drops down until he hits a = (or floor), then he executes whatever instruction is on top of that floor. Here it's the ! command, which tells Mario to stop walking.

Length 5 Snippet


This time, Mario encounters a + sign, which tells him to increase the cell under the pointer by one. Once again, he encounters a ! sign that tells him to stop.

Length 6 Snippet


What good is a language that can't output? Here, Mario encounters 2 +s (causing the cell to have a value of 2), then a : which outputs the numeric value of the cell under the pointer. This program will output 2. Also, note there is no floor: Mario falls until EOF where he stops.

Length 7 Snippet


This should output 1 - right? No, it outputs 0. That's because the ) command moves the pointer right one cell, like >in Brainf**k. ( does the same thing, but to the left instead.

Length 9 Snippet


Mario can also jump! When he encounters the ^ jump command, Mario will move up one space. There is also the > command to make him go right onto the next platform.

Length 11 Snippet


Two new commands are introduced: [ and @. [ tells Mario to skip the next instruction if the cell pointer is 0. @ tells Mario to walk the other way. Here, Mario sees the [, and since the cell is 0, he skips the @. Then he adds one to the cell (+), outputs the number (:), and walks the other way (@). This is an infinite loop.

Length 13 Snippet


Mario can also walk in different directions: the < command tells Mario to walk left. The 3 +s add 3 to the cell, and the : outputs 3. Once again, Mario falls until EOF.

Length 15 Snippet



Going down, Mario?

The # and " commands are elevators: # is the start, where Mario gets on if he is not moving, and " is the bottom, where he gets off, we need to tell mario where to go once he come out of the pipe, so we use >. He then hits two + and a :, outputting 2. I've used a down elevator, but an up one would also work.

Length 17 Snippet


Mariolang Can also use input. Here we use ; to read the imput as an integer, then we decrement our value until it reach 0, at that point we exit the loop and the program stop

  • \$\begingroup\$ Update already! This sounds pretty cool. :) \$\endgroup\$
    – Florrie
    Oct 13 '15 at 12:22
  • \$\begingroup\$ @towerofnix Had to go inactive for a while, didn't realize how popular this became. I've added 5 new snippets. \$\endgroup\$ Oct 26 '15 at 21:30


Kotlin is a statically-typed programming language that runs on the Java Virtual Machine and also can be compiled to JavaScript source code. Its primary development is from a team of JetBrains programmers based in Saint Petersburg, Russia.

Factoid: The name comes from the Kotlin Island, near St. Petersburg.

Length 1 ?

Kotlin has built-in null safety. A normally declared variable cannot contain a null value, unless that type is declared with the modifier ?. For example, var a: String = "sam"; a = null is an error at runtime. However, var a : String? = "sam"; a = null is legal.

This extends to parameters, where a possibly-null variable cannot be used where a not-null variabled has been specified.

Length 2 ?.

Kotlin allows us to chain methods together, with a short cut for nulls. So, if we did val myBoss = employee?.department?.boss?.name then, if any of the intermediate calls were null, the final result would be null and not a null pointer exception.

Length 3 out

Kotlin supports declaration site variance like Scala, but using the out keyword rather than +. In scala, trait Foo[+T] makes Foo covariant in T, in Kotlin the equivilent would be trait Foo[out T], similar to how C# does it. The idea being that a covariant type only produces values of T (outputs them), so the naming convention makes it easier to remember which way around co-variance and contra-variance work.

Length 4 data

The data keyword is used to create a data class. Eg, data class Foo(val a: String, val b: Int). The compiler automatically generates the following functions from all properties declared in the primary constructor with a val or var: equals() / hashCode() pair, toString() of the form "Foo(a="qwerty", b=42)", componentN() functions corresponding to the properties in their order or declaration, and a copy() function.

If any of these functions are manually defined in the class body or inherited from non trivial parent types, they will not be generated.

Length 5 c.foo

Extension methods are methods that can be added to an already existing type. To declare an extension function, we need to prefix the name of the method with the type we wish to extend. Eg, the following adds a method to String called take:

fun String.take(k : Int) {

Note, this inside the function refers to the receiver object. Eg, when invoking string.take(4) the this would refer to the string instance.

Length 6: inline

We can ask Kotlin compiler to inline a function, so that the overhead of wrapping a closure in an object does not occur.

Eg, given

inline fun lock<T>(lock: Lock, body: () -> T): T {
  // ...


lock(l) {foo()}

Would be compiled into

try {
finally {

Length 7: a !is B

Kotlin does not require explicit casts, but instead will smart-cast a type once an is or !ischeck is performed. For example:

// given a x of type Object
if (x is String) {
   println(x.substring(3)) // x is automatically cast to String

Now get this; the compiler is even smart enough to understand negative casts that lead to a return. For example:

// given a x of type Object
if (x !is String) return
// from here, x is available as a String

That's pretty cool.

Also Kotlin does allow unsafe casting if needed, using the as keyword. It will throw an exception if the cast cannot be performed. Eg,

val y : String = x as String

Length 8: when (x)

When is somewhere between simple switching and pattern matching. A when block will match its argument against each branch until some branch condition is satisfied. The when block is an expression so yields a value. The default case is declared with the else keyword but is not needed if the compiler can see that all cases are covered. One difference with Scala here is that the branches can invoke method calls directly (with Scala we would move that to a guard clause on the case branch).

An example:

val k :String = ... // some string

when (k) {
  isUppercase(k) ->
  isLowercase(k) ->
  else ->



Lisp is defined by its unique parenthetical notation.

Snippet (10 chars)

(+ 1 1 10)

Ok, I know I've been using + for a while now, but now this will show another side of it. One time, I showed + with 0 parameters, then 1, and now 3. This will return 12.

Snippet (6 chars)


If you're deciding to compile lisp, usually you would define the function main. This simply executes that. Otherwise it would throw an error.

Snippet (5 chars)

(+ 1)

Similarly to the three-character snippet, this adds one to nothing. It seems it should show an error, but instead, simply returns 1.

Snippet (4 chars)


Because ex is a function not defined by default, the interpreter will throw an error.

Snippet (3 chars)


+ is a function that adds all of the parameters. Because this is adding nothing to nothing, you would expect this to return an error or nil, but it actually returns zero.

Snippet (2 chars)


This is the shortest functional snippet. It simply returns nil.

Snippet (1 char)


This does absolutely nothing. It is simply a comment. There is nothing that functions in Lisp that has less than two characters. (maybe reading the Factoid would help?)

  • 1
    \$\begingroup\$ "Unique" is one word for Lisp's parentheses. I'd probably go with "excessive." :) \$\endgroup\$
    – Alex A.
    Feb 21 '15 at 4:14
  • 2
    \$\begingroup\$ @Alex Say what you wish. I stand by Lisp. \$\endgroup\$
    – robbie
    Feb 21 '15 at 14:42
  • \$\begingroup\$ Don't get me wrong, I think Lisp is great. Just lots and lots of parentheses. \$\endgroup\$
    – Alex A.
    Feb 21 '15 at 23:13
  • 1
    \$\begingroup\$ @Alex Lots of parentheses, but it's better than having all these parentheses, square brackets, and curly brackets all over the place. \$\endgroup\$
    – robbie
    Feb 22 '15 at 2:06

AppleScript (or osascript, from command line)


Applescript is a programming language most commonly used for automating events in the system environment and Aqua interface interactions in Mac OS X, though it can be used as a normal programming language as well. Its syntax boasts an (almost) English grammar method of writing, making it easy-to-use for programmers, beginners or otherwise.

Length 1 Snippet


Okay, it looks a little boring.

Basically, this is a very short operation. I take 1 and do nothing with it. Since AppleScript always returns the result of the final operation, it will print "1" to the console.


Length 2 Snippet


This keyword defines the current object being told to do something: if I was telling Finder to do something, it would return Finder. However, since I haven't defined anything for it to be tied to this is equivalent to


Which defines the top-level script object. So, at the end of the day, both of these 2-byte codes will return


Which is how AppleScript defines itself.


Length 3 Snippet

We're slowly creeping our way to show the full functionality of AppleScript...


This is the general array syntax in AppleScript. Arrays in AppleScript act more like ArrayLists in that they are not restricted as to what they may hold, and you can concatenate onto them at any time with &. (note that & is also the string concatenation symbol and in some cases may cause conflicts).


Length 4 Snippet


While this code by itself won't function due to the enormous verbosity AppleScript, this is the keyword that allows the "telling" of commands to an application. This unlocks enormous potential, from the automation of GUI interactions to changing System Settings with a click of a button.

Length 5 Snippet


This is another benefit of AppleScript: auto-complete. AppleScript is very good at golfing (not really) due to its ability to correct code. This code will not be executed. Oh no, the code that will be executed is this:

log ""

It auto-fills the space for you.

This code, as is, will print out to the "Messages" tab in Script Editor or to STDERR through osascript -e.


Length 6 Snippet


While this won't run on its own (it needs an end statement), this is one of the most important keywords in AppleScript - on its own, with no restrictions on how many times it will repeat, it will loop infinitely. The syntax relating to repeat is immense, so I won't mention it all in this snippet. It'll come back later, though.

Length 7 Snippet


Error catching in AppleScript. Piece o' cake. This may be used in instances where you are comparing possible null strings to other strings or when trying to see if true > 5. It's also very important syntax, but used less frequently in the code golf community.

Length 8 Snippet


Let's say you've lost the primary window of an application, or you want to start it. If you tell an application, even one that isn't active, to activate, it will move to the pane where it was last open (or currently open) and pull up any active windows (or start them if the application wasn't active until the point at which you told it to activate).

Example code that actually is relevant:

tell app"Finder"to activate

Runs as

tell application "Finder" to activate

Which makes the "Finder" application the primary application (for MacOSX users, this means that it's the application name in the top-left hand corner. It might have no active windows).


Length 9 Snippet


This is a command that's typically specific for the application 'System Events' - basically, it replicates the user of typing in a character.


Length 10 Snippet

set x to 1


This is how you make variables in AppleScript. Due to its verbosity, many answers for languages like CJam or Pyth will be shorter than just the variable declaration. This is why AppleScript will almost never win at golfing.

Still, though. The fact that it's also pseudocode is nice.

Length 11 Snippet

if 1<=1

A simple if statement.

This will execute as

if 1 ≤ 1
end if

Thanks to AppleScript autocorrection and bonus(!) supported characters. This is the most basic (and most concise!) syntax for if statements in AppleScript.

Note: This is actually shorter than if <conditional> then, the one-line way to do it.

Second note: Because of the extreme verbosity of AppleScript, the "correct" way to do this is with less than or equal to, but it will support <= or ≤ anyways.

Length 12 Snippet

current date

Wonder what this one does...

current date

Length 13 Snippet

the clipboard

You can gather the contents of the clipboard fairly simply with this command; when called anywhere, it will return the value of what's held currently in the clipboard. It's brother, set the clipboard to, does exactly as it sounds.


Length 14 Snippet

You know a language is verbose when the first method of input through scripting is 32 bytes long.

clipboard info

I'm not even sure what this one is... The documentation about it simply says:

Returns information about the clipboard.


This is a result for a clipboard that has been set to "" with the command set the clipboard to ""


Length 15 Snippet

Who knew AppleScript was so sassy?

summarize string

I honestly have no clue what the point of this command is. When called on datatypes, though, it does some funny things.


'A string is pretty much "TEXT"'


'Kappa, you don't know what an application is?'


'I'm kinda doubtful of reality.'

...and nihilistic, too? I'm learning a lot about AppleScript. >.>

  • \$\begingroup\$ seems like the "keystroke" snippet showcases the "current date" feature \$\endgroup\$
    – Ven
    Apr 26 '16 at 13:34
  • 1
    \$\begingroup\$ @ven Whoops, I'll fix that. Thanks. \$\endgroup\$ Apr 28 '16 at 7:05
  • 1
    \$\begingroup\$ 17 votes. Please update your answer ASAP. (don't panic though) \$\endgroup\$ May 30 '16 at 6:59



MATL is a stack-oriented language based on MATLAB and suitable for code golf. Many functions are similar to those of MATLAB, sometimes with extended funcionality.

To simplify stack handling there are clipboards, similar to variables in other languages. An interesting feature is an automatic clipboard that holds the inputs of recent function calls. This often avoids the need to manually copy.

There are different types of functions. Most are normal functions, which perform operations on inputs and produce outputs. Other types are stack-handling functions, for duplicating, deleting or moving elements in the stack; and clipboard functions, for copying and pasting elements from the clipboards.

Length 1: sum of elements in an array

The program (try it online!)


computes the sum of an array provided as input and displays it. This serves to illustrate several things:

  • Input can be implicit: if a function needs an input that is not present in the stack, it is automatically taken. The explicit form would be is, where i takes the input.
  • The stack contents are implicitly displayed at the end of the program, by default.
  • MATL, like MATLAB, has many operations that automatically operate on the contents of an array. Using terminology of other languages, s folds the addition operation over the array.
  • If the input to s is multidimensional, this function performs the sum along the first non-singleton dimension, as in MATLAB. For example, if the input is a 3×4 array (use ; as row separator), the output will be a 1×4 row array (sum along first dimension). If the input is a 1×4 row array, the result will be a 1×1 array (sum along second dimension), which is the same as a number.

Length 2: sum along columns

So what if we want the sum of each column, even if the input happens to be a row array? The following code (try it online!) does that:


These two characters together are the name of a single function, which in this case is "sum along the first dimension". Functions are always named by either one or two characters, and in the latter case the first character is always X, Y or Z.

Another form of forcing the sum to operate along the fixed dimension would be to use the s function with two inputs, and specify the desired dimension as second input (see length-3 snippet).

Length 3: ternary range


Try it online!

Many functions can take a variable number of inputs or outputs. Each function has a default number of inputs and outputs, or arity. These default can be modified by means of meta-functions. The meta-function $ specifies the number of inputs (or even their position in the stack) of the following normal function.

The function : (range) by default takes one input n, and produces its unary range. With three inputs, say i, s and f, it produces an array formed by numbers i, i+s, i+2*s, ... up to the largest integer not exceeding f.

Length 4: multiplication table

The code (try it online!)


produces an n×n multiplicaton table, where n is an input number.

  • : by default it takes 1 input, and produces the row array [1,2,...,n].
  • t is a stack-handling function. It also takes 1 input by default, and simply duplicates it. Other stack-handling functions are w (swap elements) and b ("bubble up" and element).
  • ! is transposition, so the row array at the top of the stack becomes a column array [1;2;...;n].
  • * corresponds to multiplication. By default it takes two inputs. Like most arithmetic operators, it works element-wise with broadcast.

The latter means that repetition is implicitly applied along singleton dimensions if needed. In this case, the two arrays have non-matching dimensions 1×n and n×1. Thus the first array is implicitly replicated n times along the first dimension, and the second along the first dimension, so that they can be multiplied element-by-element. This produces all "combinations" (in the sense of Cartesian product) of the operation.

The result is a 2D numeric array. Numeric arrays are displayed as numbers separated by spaces with vertical alignment.

Length 5: display "all" even numbers


This uses an infinite loop, specifically a "do...while" loop in which the loop condition is always true. Try it online! (but kill it immediately).

A "do...while" loop begins with ` and ends with ]. "End" statements ] at the end of the program can be omitted, because the loop is implicitly closed in that case.

In a "do...while" loop, when the (possibly implicit) statement ] is reached the top of the stack is consumed, and if it's truthy the code proceeds with the next iteration. An array is truthy if and only if it is non-empty and all its elements have nonzero real part. In this case a T literal (true, corresponding to a logical 1) is pushed at the end of each iterartion, so the loop goes on forever.

The body of the loop pushes the iteration index with @. Note that iteration indices start at 1. Then E doubles that number, and D displays it. In this case we cannot rely on implicit display at the end of the program, because this program never ends.

Length 6: Separate primes from non-primes


This code accepts as input an array of positive integers, and produces two arrays: one with the primes contained in the input, and one with the non-primes. Try it online!

The code is based on logical indexing, which means using an array of type logical as an index. This works as in MATLAB: true values in the index specify which entries to use. So for an array [10 20 30 40], the index [false true false true] refers to the subarray formed by the second and fourth entries, that is, [20 40].

If we wanted to only pick the primes from the input, the code would be tZp): duplicate the input (t), check for each entry if it's a prime (Zp), and then use the second array as an index into the first ()).

) is one of the several indexing functions in MATL. Specifically, it does reference indexing, which means extracting elements from an array. (This contrasts with assignment indexing, whereby specified positions of an array are written with new values). The ) function, like others used for reference indexing, has a two-output version, which produces the indexed array and the "complementary" array, corresponding to the entries not selected by the index. The meta-function # specifies the number of outputs of the following normal function. So in this case 2#) produces the primes and then the non-primes in separate arrays.

Length 7: Separate digits from non-digit characters


This snippet is similar to that with length 6, but serves to illustrate two new aspects: predefined literals and meta function &. The code takes a string and separates it into two strings: one formed by the digits and one with the non-digits, maintainig the order they have in the input. Try it online!

Y2 is one of several functions that produce predefined literals depending on its numeric input. In this case, 4Y2 gives the string '0123456789'. Function m takes two inputs by default, and outputs a logical array that contains true for elements of the first input that are present in the second. This is then used as logical index into the original string, which was duplicated (t) at the beginning.

2#) would then produce a substring with the digits and then a substring with the remaining characters. But &) can be used instead.

Most functions allow an alternative or secondary default input/output configuration. Meta-function & is used for this purpose. For ), using & corresponds to selecting two outputs, so &) is equivalent to 2#). Thus the code produces the stated result.

The meaning of & is function-specific. For example, for : it affects the number of inputs. A way to see this is to display the function's help using option -h of the compiler:

>> matl -h :
:   vector of equally spaced values
    1--3 (1 / 2);  1
    colon (with three inputs x, y, z produces x:y:z; with two inputs 
    x, y produces x:y). If one input: produces 1:x 

The line 1--3 (1 / 2); 1 describes the possible numbers of inputs and outputs. This function takes a variable number of inputs from 1 to 3, and produces 1 output. The default number of inputs is 1, and the effect of & is to change that to 2.

Length 8: filter square-free numbers

The code


takes an array of integers and outputs those integers that are square-free. A number is square-free if it can't be divided by a perfect square other than 1. Equivalently, in the prime factor decomposition of a square-free number no prime appears more than once. This code serves to illustrate some control flow structures, namely for loops and if branches. Try it online!

Statement " begins a for-each loop: it takes an array as input and iterates over its columns. Within the loop, @ pushes the current iteration variable, that is, each column of array. In the present case the input is a row array, so each column is just one number. Yf takes that number and pushes its prime factors. d computes the differences between consecutive elements, so a square-free number will not produce any 0. A with a vector as input gives true if all the elements are nonzero. So the output of A tells if the current number is square-free or not.

Following is an if branch: ? takes an input and if truthy executes the next statements. In this case there is only one statement, @, which pushes the current number (which was found to be square-free).

Control flow structures are normally ended by ]. In this case, the two ] statements are implicit at the end (as in the length-5 snippet). Using the compiler with the -e option shows the code including the implicit statements, as well as automatic comments, which may be useful as a starting point for an explanation of the code, with indentation:

>> matl -e "@YfdA?@

"          % for
  @        % for loop variable
  Yf       % prime factors
  d        % difference
  A        % all
  ?        % if
    @      % for loop variable
           % (implicit) end
           % (implicit) end
           % (implicit) convert to string and display

Length 11: Matrix multiplication, manually


This illustrates the use of multidimensional arrays. These are a powerful tool, specially when coupled with dimension permuting and broadcasting. The code takes two matrices and computes their matrix product (which could also be computed with the Y* function). Try it online!

Function 7L pushes the predefined literal [2 3 1], and &! applies that permutation of dimensions to the first (implicit) input. Let this input be an M×N matrix (2D numerical array). The permutation with [2 3 1] means that the 2nd dimension becomes the first, the 3rd becomes the second, and the 1st becomes the third. Since the input is a matrix, its 3rd dimension is actually a singleton dimension, that is, the size along that dimension is 1. In fact, any array can be assumed to have arbitrarily many trailing singleton dimensions. So the input matrix can be interpreted as an M×N×1 3D array, which after the permutation becomes an N×1×M array.

Function * takes a second (implicit) input and multiplies it by the previously obtained 3D array. The multiplication is element-wise with broadcast (see length-4 snippet). The second input has size N×P, or equivalently N×P×1, and the result of * has size N×P×M. To obtain the matrix product, a sum is carried out along the first dimension using Xs. Note that the first dimension of the N×P×M array corresponds to columns of the first matrix and rows of the second matrix. The result of Xs has size 1×P×M.

6B pushes 6 in binary, that is, the logical array TTF (or [true true false]). Then e is applied to collapse the first two dimensions of the 1×P×M array. This works as follows. e is used for reshaping arrays, and takes two inputs by default. With a logical array as second input, it collapses consecutive dimensions of the first input that have the same logical value in the second. So in this case it collapses the first and second dimensions, producing a P×M matrix.

Finally ! transposes the matrix to yield the M×P final result.

Length 12: show a simple image

The code


takes two inputs and shows the following image (example for inputs 200, 150). Try it at MATL online!

enter image description here

: takes an input w and generates the row vector [1 2 ... w]. i:! takes a second input h and produces the column vector [1; 2; ...; h]. + creates an h×w matrix with all pair-wise additions.

t0) creates a copy of the matrix and extracts its last element. This uses linear indexing: a single index is used to access a two-dimensional array (matrix) in column-major order, i.e. down, then across. So for a 2×3 array the linear indices would be

1 3 5
2 4 6

The index is interpreted in modular sense. This means that indices out of bounds are interpreted cyclically. The period of the cycle is the size of the indexed dimension; or, for linear indexing, the total number of elements of the array. So in the 2×3 example a linear index 8 is the same as 2. 0 always corresponds to the last value in linear order, that is, last column and last row.

Thus t0) is the last element of the h×w matrix of pair-wise additions. By construction, this is the largest value. So the following / normalizes the array to maximum value 1. Finally, YG is a function for displaying or saving images. It takes two inputs by default, and the last input specifies what the function actually does. 3 means that the function displays the matrix (first input) with each entry corresponding to one pixel on the screen, using a grey colormap by default.

  • 2
    \$\begingroup\$ .......5 and 6? \$\endgroup\$ Apr 4 '16 at 22:29
  • 1
    \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ :-) 5 is almost ready. I hope I'll have time tomorrow! \$\endgroup\$
    – Luis Mendo
    Apr 4 '16 at 22:30
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ 5 included. Currently thinking about 6... \$\endgroup\$
    – Luis Mendo
    Apr 5 '16 at 22:42
  • \$\begingroup\$ 7, 8, 9, 10, 11? \$\endgroup\$ Apr 30 '16 at 3:33
  • \$\begingroup\$ @CatsAreFluffy Working on that :-) \$\endgroup\$
    – Luis Mendo
    May 1 '16 at 2:44

Delphi (also known as Object PASCAL)

Factoid: Over the years the name of Delphi changed prefixes many times. Beginning with Borland Delphi. This name held for ~13 years until it got renamed to Embarcadero Delphi in 2008 (as you may assume Embarcadero bought Delphi).
The code is similar to C++, but is more object oriented and is translated from PASCAL to C++ during compilation. Recent versions are also able to generate applications for all major OSes including Windows, OSX, Linux, Android and even iOS.

Downsides are: Delphi is built together with VCL (Visual Component Library) which slows down the performance of graphic-heavy applications a lot (every change of properties of a visual object will cause a redraw of the component), but the IDE is even simpler to use (drag and drop of components).


Because a line-ending semicolon (;) is optional before a closing end; tag, I may omit it to save characters.

Length 1:


Yes, I know. It's very basic, but is compiled without throwing errors, warnings etc.
It will be compiled into a simple NOP statement doing nothing.
This may be helpful, if the IDE removes empty procedures, to make sure you remember to program them.

Length 2:



This will simply run the procedure D without any arguments. In Delphi there is no distinction of lower- and uppercase names (functions, procedures, variables even files in the compiler directive) and functions or procedures (two different types of jumping to code and returning back) can be called as well as be declared without braces (()) if they don't request parameters.
This above means, that the procedure/function could be called either d or D and could be declared with or without braces. The compiler takes care of managing this.



This places a label at the current location. You can then use goto L; to jump to that label, which allows skipping code or alternative loops.
You just need to make sure that you declared the label in the function/procedure head (label L;)

Length 3:


Yes, Delphi allows inline assembly code!
This snippet is the opening tag for assembly code, but have to close it with end; of course else it will spam compiler errors.
Inside the asm [...] end; block you can use your beloved assembly with all the variables used in usual Delphi.

Length 4:




Those two are functions returning the actual date or time of the day of the type TDateTime. Funny enough TDateTime is just an alias for Double with no changes at all. Using DateToStr or TimeToStr every Double can be converted into the actual Date/Time.

Length 5:


Bam! This procedure frees the current object (ie. safely destroying it). If you do it on one of your forms this closes the window but keeps the process (event queue, primary thread etc.) running. If an object is currently being created, calling Free; will throw an access violation error.

Length 6:

goto l

(Assume l is an already defined and set label)
Tired of while True do loops? Use labels and gotos!
If you put a call in the line before an end; you don't need a line-ending ; (semicolon). Very handy.

Length 7:


Some bitwise operations, yay! This function swaps the first half of a SmallInt (16 bits) and the second half. Example: 8 (0000 0000 | 0000 1000) becomes 2048 (0000 1000 | 0000 0000).
It doesn't matter which size the integer actually has, it gets converted to a SmallInt by truncating/filling with zeros.

Funny side-note: Usually all functions are declared anywhere, especially when exploring their declaration, but Swap (as well as a few others) are not found in the source of their declaration file (System.pas) but the declaration is displayed correctly.

Length 8:


If you call this in a component's thread (which is usually your main thread), this will schedule all child components and itself for repainting. This is usually not needed, but if you modify components outside of the main thread (eg. in a secondary thread) the components do not get invalidated nor repainted, thus needing this procedure. This procedure also has an alias called Refresh;.

Length 9:


Trim(' ')

This function takes a string and trims (ie. removes) all leading/following spaces (no other character(s)) and returns the trimmed string.
There are even functions to trim only one side (left or right).



Right, Delphi doesn't use curly brackets in code, but rather as the opening/closing tag of a comment. There are two types of declaring a comment:

  1. curly brackets like above ({}).
    They allow multi-line comments. You can replace those curly brackets with (* *), if you are not able to use those.
  2. double forward slashes (//).
    Many languages feature them, so does Delphi. The end of the comment is the next line break, so use this for small notes.

Length 10:

{$R *.dfm}

"What is this?", you might think. It seems like a comment I just characterised above. But it isn't;
it's a compiler directive! It tells the compiler to add a file named the same as this Unit (that's how source files are called in Delphi), but with the extension .dfm, which is the common file type of a form.
Compiler directives can be identified by the $ as the first character in curly brackets.

Length 11:


Some more things you can do with windows/forms you have control of (which should be all of them; unless the system denies permission, which may happen on windows owned by processes of the System user).
This procedure will put the window to the back of the stack without losing focus. This may be useful for something, but hiding a form/window moves the focus to the next one and doesn't keep the actual window open and focused.



Length 18 snippet

(min-width: 700px)

This is part of a media query, which allows certain styles to only show for certain media. Perhaps the most common is min- and max-width, which is the basis of responsive web design, allowing the site to look different depending on the device width. While a news site might expand to fill a widescreen monitor by fitting several stories next to each other, on a phone there is only enough room for one.

The most common way of using media queries is within a stylesheet: the rules are surrounded by {} brackets, prefixed with @media ([rule]), like so: (click "Full page" to see the background color change from tomato to turquoise)

body {
  background-color: tomato;

@media (min-width: 700px) {
  body {
    background-color: turquoise;

Media queries can also tell you even more data about a device, such as its resolution, color, and orientation.

Length 15 snippet


Another pseudo-selector, this selects all <input>s that are checkboxes (or radio buttons or dropdown options) that have been selected by the user. This gives CSS an unintended way to register clicks, allowing for everything from tabs to a reaction time test.

These work by having a <label> for the checkbox that checks the box when clicked anywhere on the text. The checkbox is hidden, leaving just the label. Then the adjacent sibling selector + is used to select the label. Here is a simple example (click "Show code snippet").

input:checked + label {
  font-weight: bold;
  color: red;

input {
  display: none;

label {
  display: block;
<input type="radio" name="foo" id="radio1" />
  <label for="radio1">Click me!</label>

<input type="radio" name="foo" id="radio2" checked />
  <label for="radio2">Click me!</label>

<input type="radio" name="foo" id="radio3" />
  <label for="radio3">Click me!</label>

Length 14 snippet

columns:4 12em

CSS has the ability to break up long text into several shorter columns, as commonly found in newspapers. The columns property above is shorthand for column-count: 4; column-width: 12em, which tells the browser to break the text into at most 4 columns, at least 12em wide. There are more related properties that allow you to control other aspects, such as gap and rule between columns.

Length 12 snippet


This is the code to make flexboxes, which do just what you think: make boxes flexible. This does away with hacky methods developers used and adds a lot of functionality. CSS-Tricks has an excellent guide to all things flexbox that explain them in more detail.

Length 11 snippet


This is a pseudo-class that selects each element that is the last child of its parent. For example, take the following HTML code.


A selector of p:last-child would match the Baz paragraph because it is last. However, if there were a different element, say <blockquote>, after Baz, that selector would match nothing because there is no <p> that is the last child. For this, you would use p:last-of-type, which ignores all non-paragraph elements and finds only the last <p>, regardless of whether it is last overall.

A useful cousin of this selector is :nth-child. It is clear that :nth-child(3) would match the third element, but you can also use more complex queries, such as :nth-child(2n+1), which matches every other element. This is useful for styling every other row of a long table for easy contrast. Mozilla Developer Network lists several ways to powerfully use nth-child.

Length 10 snippet


This causes other, more specific rules to be overridden. It is placed after a declaration, before the semicolon. Note that in most situations, you should not use this, because it can make debugging a nightmare, but I will take this opportunity to talk about specificity, which is where the "cascading" in CSS's name comes from.

This basically means that a declaration that applies to a few elements (i.e. it's more specific) will be used in favor of a declaration that applies to more elements. For example, take these HTML and CSS snippets (click "Run code snippet" to see what happens):

.green { color: green; }
#red { color: red; }
* { color: blue; }
p { color: yellow; }
<p class="green" id="red">Foo bar</p>

You'll notice that even though all three rules match the <p> element, the red color gets applied because it is the most specific: as mentioned below: #red is an ID, which should be unique to only one element, while you can have any number of green classes or <p> elements. The complete specificity order is found in the Mozilla Developer Network page linked above. In the following snippet, nothing has changed except for the addition of !important, but it causes the universal selector, which is the least specific, to take precedence over all the others.

.green { color: green; }
#red { color: red; }
* { color: blue !important; }
p { color: yellow; }
<p class="green" id="red">Foo bar</p>

Length 9 snippet


This property is pretty self-explanatory: it defines the maximum width an element can have. One common example usage is for a webpage that has large amounts of text, such as a blog post or news article. You would want the text to take up as much horizontal space as possible on any device, so you'd set the width of each paragraph element to 100%. However, on wide screens, lines become too long to navigate comfortably, so you might set the max-width to 1000px so the width stops increasing after the window is wider than 1000 pixels. Predictably, there are also min-width and max-height properties.

Length 8 snippet


This creates a pseudo-element (slightly different from the pseudo-class in the length 6 snippet below) after every <q> element, which can be separately styled from the <q> itself. This is commonly used with the content property, which allows you to add text that will show up after the element. <q> is used to designate inline quotations, so you would add the declaration content: '"' to automatically add quotation marks after every quote.

As you might guess, there is also a ::before pseudo-element which does the same thing, except before the element. The two of these working together can be used to make all sorts of shapes like a heart or star using only one HTML element and CSS (which is based on the box model). You can see many of these and their code on CSS-Tricks.

Length 7 snippet


This is one of the shortest possible full "programs" that can actually do something. It demonstrates the format of a CSS rule: before the braces is the selector, which is usually an HTML tag, class, or ID, but it can also be more advanced, like some of the snippets below. The b in this example selects every HTML <b> (bold text) element.

The inside of the braces are the declarations. (The closing brace of the last rule is optional.) Each declaration is a pair of property and value, separated by semicolons (again, the last semicolon is optional). In this example, top is the property, 0 is the value, and they are separated by a colon. A more readable and realistic version of the above would be:

b {
  top: 0;

Length 6 snippet


This is a pseudo-class selector that is applied when an element is hovered over with the mouse. You see this all the time, for example in comments on a Stack Exchange site that show upvote and flag buttons on hover, or links that change color when you mouse over them. There are other state selectors like active, focus, and visited.

Length 5 snippet


This is a selector to match any element with the alt attribute (most often used for specifying alternative text if an img cannot be displayed), regardless of what it is or if it is empty. You can use [alt=foo] to only match elements with an alt value of foo. There are several others for attributes containing, beginning with, and ending with a value.

Length 4 snippet


CSS uses hex triplets to specify color, which consist of three two-digit hexadecimal numbers, two each for the amount of red, green, and blue present in the color. If both digits in each set are the same, as in #3388bb, it can be shortened to just the first digit of each, as in the snippet above. There are 224 = 16777216 possible colors. The color is shown below:


Length 3 snippet


This matches a <p> (paragraph) element with the ID s. IDs are similar to classes, which are explained below, except classes can be used on any number of elements and an element can have multiple classes, whereas each ID should only be used once, and elements can only have one ID.

IDs can also be used as targets, where a link to an ID links directly to that element on the page. For example, a link to this question ending in #49172 will link directly to this answer, because it has ID 49172. You can chain IDs and classes: .a#b.c matches an element with ID b and classes a and c.

Length 2 snippet


This matches an element with the class a, used for styling multiple instances of a style. For example, you might use <a class="external"> for styling only external links, different from all links.

Length 1 snippet


This is the universal selector. It matches any element on the page, although it is the most expensive selector.


CSS (Cascading Style Sheets) is not your typical programming language, as it is used for styling HTML web pages, but I thought it still would be interesting for this challenge.

CSS came at a time when design on the Internet was a mess, with designers abusing HTML for styling purposes (<table> has never been the same). Adoption wasn't consistent across browsers, causing headaches for designers who had to resort to "hacks" to get their code to work cross-browser. These different implementations continue to this day, although much better, in the form of vendor prefixes.

  • \$\begingroup\$ Maybe show off your color! ![](http://dummyimage.com/100x100/38b/38b.png) \$\endgroup\$
    – Lynn
    May 12 '15 at 15:45


(View them here!)





\prod _{n=1}^x n

This is the factorial function, using a product instead of x!.



FINALLY! We have a bracketted equation! This is a single-element array containing the equation x*x.



This is a fraction with -3 on top and x^2 on top.


-x^2/\cos x^2

Where are your parents now! This creates a sick-looking equation.



This equation shows all possible values for which the above holds true. This tells us that Desmos can show an extreme amount of detail, and is not your average calculator.



(note the trailing space) This solves for the variable x, that is, x = -0.90673034 or 1.2746098.



(There is a trailing space, mandatory as per this meta post) This creates a lovely parametric equation i.e. tight-ish spiral.


3x\ge 4y^2

Desmos supports inequalities of nonlinear quality! This produces the inequality 3x ≥ 4y2 and graphs it.


\theta _2

This shows that Desmos supports the explicit \theta variable, which prints like this: θ. The _2 is a subscript, so the full result would look like this: θ2. This formula also shows a quirk of how bytes are counted in Desmos: though the space could be removed and still have the same copy-and-paste result, the result that is copied from Desmos forms the byte count. This will also explain why no results with parentheses, etc., have thus been posted; since copying a pair of parentheses would result in \left(\right), a 13-byte expression, these will not be posted until around ~14+ votes.


\cos bx

When Desmos encounters an undefined variable, Desmos creates a small popup:

When you click on that button, the following formula will be inserted in the slot after the original function:

Pressing the play button will allow you to "phase" through values of b, seeing the display update. Check the link above to observe this behaviour. This also shows Desmos's support for implicit parenthesis in a trigonometric function, so long as all of its inputs are "attached" with multiplication or division operators. (The latter only happens when directly copy+pasting the code into the editor.)


\sin x

Desmos supports trigonometric functions, defined like that in (La)TeX. This draws a graph, as the variable x is taken to mean an equation variable.



A function of y… how cool is that!? Something your ol' TI-84 can't do…



This is an implicit definition of an equation (implied is f(x)). This draws the graph of aforementioned function. (Also shows that Desmos will interpret a number next to a variable to mean multiplication, that is, coefficient multiplication.)



Desmos supports the definition of variables.



Desmos supports decimal numbers without the leading zero.

1-vote (thanks!)


Numeric literal. Comment: Up until about 5-7 votes, you'll be getting interesting numbers.


Desmos is an online graphing tool to help those in the mathematical field to visualize problems like trigonometry, basic derivation, and even 3D graphs!

  • 1
    \$\begingroup\$ Judging from the snippets so far, I don't know what you can do with less than about twenty characters, but impress me. \$\endgroup\$
    – lirtosiast
    Sep 29 '15 at 2:03
  • \$\begingroup\$ @ThomasKwa Thanks ^_^ I will. \$\endgroup\$ Sep 29 '15 at 2:13
  • 1
    \$\begingroup\$ Link for the interested \$\endgroup\$
    – DanTheMan
    Sep 29 '15 at 3:07

Inform 7

Inform 7 is a natural language based programming language for Interactive Fiction.


Inform 7 is among the easiest languages to read, and was surreptitiously featured in why the lucky stiff's printer spool book. His code and the game it compiles to can be played online.

Length 3


Inform 7 is a rules based language. The standard library defines many rulebooks and the player can define more. These rules are used for event handling and to create extensible procedures. Each rulebook can contain several rules, which consist of a rule preamble, and a body. The rule preamble is at a minimum the name of the rulebook, but it can also have many additional conditions.

In this example the rulebook preamble is the name of the rulebook X, and the body consists of a single phrase (function) Y. Inform 7 code is usually much more verbose than this, so these short examples will not be able to showcase the natural language aspects of the language ;).

Length 4


Each rulebook has a name and a basis: a variable type which is the main parameter for the rulebook. When you call a rulebook you can optionally call it for a particular value, which must match the type of the basis.

When a rulebook is called it goes through the rules in order and runs whichever rules have matching preambles. The preambles can specify that they want to run only for a particular subclass of the basis, only for values which meet a specific condition, or only for a single specific value. Rulebooks normally run all the rules with a matching preamble, but rules can stop it from continuing. The rules of a rulebook are automatically sorted in order from most to least specific so that if only one rule will be run, it will be the most specific one (though rules can be manually repositioned).

This example specifies a rule preamble for the rulebook X. YY could be either a subclass of the basis, an adjective phrase which checks whether the value matches some condition, or a particular object called YY.

Length 5


Here's the first example of real code! Text in Inform 7 can either be a simple literal string, or a dynamic text with substitutions which are processed at run time. Under the hood these texts are compiled to functions, but they are entirely interchangeable with simple literals.

Text substitutions can run essentially any other phrases/functions, and can be passed arguments too. Many come predefined in the base library. This example, the to say s phrase, will print an 's' if the last number printed was not 1. Similar substitutions can be used for entire sentences to output the correct grammatical inflections for a particular narration style (such as first person past tense or third person future tense), even allowing the narration style to be changed at run time.



Hexagony is a 2D esoteric language made by Martin Büttner based on hexagons. Not only the programs self are hexagons, but the memory model of terror is also based on hexagons. It took me quite some time to understand the model of terror, but eventually I still don't get it. First time I programmed in this, I was happy to get anything outputted, but after a while I realised that this is a very interesting language, with a lot to discover. I would definitely recommend programming in Hexagony.

Length 1 snippet (try it here)


Or in hexagon form:


Let's talk a bit about the memory model in Hexagony. Every memory edge has a standard value, 0. This is different from some other models, which are standard null. The second thing which makes this memory model different, is that the data kept in the memory edges are always numbers. No strings, lists, tuples and so on. For this program, I'm going to introduce you to the command !. This outputs the decimal representation of the current memory edge. ; would do the same thing, but outputs the ASCII representation.

So, you can already expect what this is going to do. This is going to print an infinite amount of 0. After running in the online interpreter, immediately kill it. It won't stop, ever.

Length 2 snippet (try it here)


Or in hexagon form:

 ! @
. . .
 . .

So, you might be wondering... When can you make this stop? That is done with the @ command. After reaching this point, the program terminates. That means we can now safely output one 0 with the program. Another thing you might be wondering is 'What are all those dots doing there?'. That brings us to the next command, the no-op .. When the pointer comes to a no-op, it will not do anything and continues its way in the same direction. This means that !@ and !@... and !@..... are all the same and give the same output. However, if we add another dot: !@......, this would give a bigger hexagon, since the maximum amount for a two-sided hexagon is smaller than the length of the program. It would give the following:

  ! @ .
 . . . .
. . . . .
 . . . .
  . . .

Length 3 snippet (try it here)


Or in hexagon form:

 9 !
@ . .
 . .

First of all, decimals in the program will be added to the current memory edge. If the memory egde = 402 and passes by a 3, the new memory edge will contain 4023. Same counts for letters, which replaces the memory edge with the ASCII value of the letter. I'll now explain how pointers move in Hexagony. But first of all, there isn't just one pointer. There are six. Each in every corner:

  0 . 1
 . . . .
5 . . . 2
 . . . .
  4 . 3

They all point clockwise, so 0 would go to the east (E), the 1 would go to the southeast (SE) and so on. The standard active pointer is 0, and you can switch the active pointer using the [ and the ] command. The next thing is, what happens when they get out of the board? When they leave at a non-corner point, they will enter the board again in the other half of the program (pointer starts at A):

   . . . .        . F . .        . A . .        . . A .
  A B C D E      . . G . .      . B . . F      . . B . .
 . . . . . .    A . . H . .    . C . . G .    . . C . . G
. . . . . . .  . B . . I . .  . D . . H . .  . . D . . H .
 F G H I J K    . C . . J .    E . . I . .    . E . . I .
  . . . . .      . D . . K      . . J . .      F . . J .
   . . . .        . E . .        . K . .        . . K .

If the pointer leaves from a corner, it depends on what value the current memory edge has (from A to B):

                     memory > 0            memory <= 0

     . . A ->          . . .              -> B . .
    . . . .           . . . .               . . . .
-> B . . . .         . . . . A ->          . . . . A ->
    . . . .           . . . .               . . . .
     . . A ->       -> B . .                 . . .

So the order of operations in this program is 9, !, @, which will output 9.

Length 4 snippet (try it here)


Or in hexagon form:

 ! $
! ) .
 . .

First, it begins at the top left !, so this will output 0. After that, it goes to the $, which is a jump. This will skip the next command, which is !. So the 0 isn't outputted twice. After that, the pointer gets to the ). This is an increment command, which just adds 1 to the current memory edge. After that, the pointer leaves the hexagon in the right corner and re-enters at the bottom left (see previous snippet to see why). As you can guess, this will output 012345678910111213141516171819202122232425....

After running in the online interpreter, immediately kill it, it won't stop.

Length 5 snippet (try it here)


Or in hexagon form:

 H ;
i ; @
 . .

This one is quite easy and simple. First, the pointer gets to the H, which pushes the char value of H. The ; will output the char H. After that, when the pointer comes to the i, the value of the memory edge will be replaced by the value of i. This will be printed by the second ; and terminates because of the @.

This will output Hi.

Length 6 snippet (try it here)


Or in hexagon form:

 4 0
; ) ;
 ( .

The new thing here is that it appends two different numbers to the memory edge. After going through the 4 and the 0, the memory edge has the value 40. This is in ASCII (. After that, the program will output this character and adds one up to the memory edge. That gives us 41, which is the closing parenthese ()). After outputting this character, the program decreases the current memory edge by 1 and goes into an infinite loop. The output will look like this: ()()()()()()()()()()...

After running in the online interpreter, immediately kill it, it won't stop.

Length 7 snippet (try it here)


Or in hexagon from:

 ? }
? " *
 ! @

This is where the memory model of terror begins. What this does is taking 2 integers (these have to be positive or both negative), multiplies them and outputs the result. I'll explain this with the hexagonal memory model:

enter image description here

In the beginning, the memory model starts at the a. The ? pushes the input onto the memory edge a. After that, the } switches to the right memory edge, which is b. There we push the input to the memory edge b. The " moves the memory pointer backwards and to the left, which is c. The * calculates the product of the two neighbours, which are a and b, prints it and terminates.

In pseudocode:

a = input()
b = input()
c = a * b

Length 8 snippet (try it here)


Or in hexagon form:

  / + !
 = / 1 }
~ . . . .
 . . . .
  . . .

Yes, this gives us a size 3 hexagon. That is because the program can't fit in a size 2 hexagon. In the hope to create a Fibonacci sequence, I ended up with this. It gives the following sequence:


I don't even know how this can output something. I probably made a mistake in my head or something, because I can't visualize what is actually happening.

Thanks to FryAmTheEggman, this does output something Fibonacci-like:


The end part is always the same (2, 42, 842, 6842). This is quite interesting and I'll try to find a more describable pattern.

After running in the online interpreter, immediately kill it, it won't stop.

  • \$\begingroup\$ I'm upvoting this, even if it means beating my answer. Hexagony is so fun! \$\endgroup\$
    – user46167
    Dec 17 '15 at 20:27
  • \$\begingroup\$ Fibonacci can be done in 6 with no separator, and 18 with, afaik. \$\endgroup\$ Dec 18 '15 at 18:15
  • \$\begingroup\$ I've figured out what your code is doing, each time it goes around the loop, the 1 is messing up your logic. The values being printed out are: 1, 12, 132, 1442, 15742 ... \$\endgroup\$ Dec 18 '15 at 20:04
  • 1
    \$\begingroup\$ +1 for "I still don't get it" \$\endgroup\$
    – user45941
    Jan 15 '16 at 7:27
  • \$\begingroup\$ I was revisiting a bunch of these, and I realised that I never explained what was happening. Oops :P Anyway, your code does: F_n = (10 * F_n-1 + 1) + (10 * F_n-2 + 1). \$\endgroup\$ Apr 5 '16 at 3:03


Note: All snippets will be shown as if they were entered into a clean REPL.

39 bytes

Charcoal> UONNO_¶_OAKAαA№αOβHWψβ«A§α§⌕AαO‽βXA№αOβ

This is an animated example, so REPL output is not shown. It's also the submission for Make a Bubble-wrap simulator. It uses the AssignAtIndex (A§) command, which, when used with the Cells datatype (obtainable from Peek commands), changes the canvas.

30 bytes

Charcoal> ×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸M↑__↖←¤:↗¤≕Pi

This is the (noncompeting) submission for Bake a Slice of Pi. It shows the (very unfinished) Wolfram Language support.

11 bytes

Charcoal> G↘↗↘↗↖↙↖↙⁵#  
    #       #    
   ###     ###   
  #####   #####  
 ####### ####### 
 ####### ####### 
  #####   #####  
   ###     ###   
    #       #    

Polygon(:DownRight, :UpRight, :DownRight, :UpRight, :UpLeft, :DownLeft, :UpLeft, :DownLeft, 5, '#'). An example of a more complex polygon.

10 bytes

Charcoal> G↗↘←⁴*#M↓*

Polygon(:UpRight, :DownRight, :Left, 4, '*#'); Move(:Down); Print('*'). An example of multi-character fill in Polygon.

9 bytes

Charcoal> ┌┐‖M↓

Print('┌┐');ReflectMirror(:Down). Another ASCII-art oriented builtin. Note that and count as three bytes each.

8 bytes

Charcoal> P+abcUB*

Multiprint(:+, 'abc');SetBackground('*'). A very useful builtin in many situations.

7 bytes

Charcoal> B⁵¦⁵123
1   3
3   1
2   2

Box(5, 5, '123'). Demonstrates one of the many builtins with overloads for strings of length greater than 1.

6 bytes

Charcoal> aJ³¦³a


This isn't a very interesting one - Print('a');Jump(3, 3);Print('a'); but it demonstrates the separator ¦, useful when you have two numbers or two strings in a row.

5 bytes

Charcoal> G↗↘⁴_

An alternate syntax for Polygon - Polygon(:UpRight, :DownRight, 4, '_'), also demonstrating its autofill feature, when the cursor does not end up in the starting position.

4 bytes

Charcoal> G+⁵a

In verbose mode, this is Polygon(:+, 5, 'a'). Self-explanatory. Any identifier with a preceding : is attempted to be parsed as a direction.

3 bytes

Charcoal> WSι
Enter string: a
Enter string: sdf
Enter string: 


This is a while loop. In verbose mode this is equivalent to:

While(InputString()) {

Loop variables are automatically chosen as the first free variable (greek letter starting at iota and wrapping around after omega). Truthiness is the same as Python truthiness.

2 bytes

Charcoal> ‽⁵

This demonstrates the syntax for operators, in this case a monadic Random operator. The syntax for integers can also be seen here, which is just a run of superscript digits. This returns an integer, which is implicitly printed as a line of that length using a character in \/-| depending on the direction of the line. In verbose mode this is Random(5).

1 byte

Charcoal> a

Expressions are implicitly printed if they are not preceded by a command character.


This language was designed specifically for ASCII-art challenges. The 95 printable ASCII characters aren't used as commands, so string literals are not delimited.


Z80 Machine Code


The Z80 is probably the most famous CPU developed by Zilog. The company Zilog was started by dissatisfied Intel employees and their first CPU, the aforementioned Z80, was fully compatible with Intel's 8080, as well as having its own set of extended instructions. This was a big selling point as it meant that CP/M (a very popular OS in its day, designed for the 8080) could be run on a computer using a Z80 CPU with no changes to the software.

Length 1 snippet:

HEX Op code   Instruction name
-----------   ----------------
AF            XOR  A

Being an 8-bit processor, the Z80 has many 1-byte instructions of varying usefulness. On the surface this instruction would not seem to be particularly useful as what it does is calculate A XOR A, storing the result in A. However, since the result is always 0 and all other ways of setting A (the Z80's main register or Accumulator) to 0 are longer than 1 byte, that makes this an interesting and useful instruction! It also has the side effects of setting the Z Zero flag (to 1) and resetting the C Carry flag (to 0). If you don't mind losing the previous value in A this is also a shorter way of resetting C, although there are other non-destructive ways of resetting C in one byte. The more obvious way takes two bytes.

Length 2 snippet:

HEX Op code   Instruction name
-----------   ----------------
10 nn         DJNZ n

This is a combination instruction. Its full name is Decrement Jump Non Zero. It combines Decrement B (DEC B) with Jump Relative Non Zero (JR NZ, n) for a saving of one byte (very important for code golf!) It is also 3 T-states faster than using the two instructions separately, the actual time taken being dependant on the CPU's speed, typically 4 MHz. There is no other register that can be used instead of B and the only test for the jump is NZ, making this instruction unique because most other instructions have "siblings" such as the 75 different 8-bit load (LD) instructions.

If the value stored in B (an 8-bit register) is zero after being decremented, the program jumps n bytes, where n is a signed 8-bit integer. This means n can be anywhere from -128 to 127. The closest analogy with higher languages is the FOR loop where the code is executed B times. If B already contains 0 the first time DJNZ is executed, B gets decremented to 0xFF (-1 / +255) resulting in the loop executing another 255 times.

The simplest form is 10 FE # DJNZ -2 which jumps back two bytes (to itself) until B is zero. All this would do is make sure B is zero and delay the execution of the following code by an amount proportional to the initial value of B. Alternatively, the offset could be a positive amount, skipping the subsequent code the first B times. Interestingly, this instruction affects no flags, not even the Zero flag so extra size/time savings and/or more straightforward code can be obtained if it is wanted to pass the current value of Z to another part of the program.

Length 3 snippet:

HEX Op code   Instruction name
-----------   ----------------
DD 77 nn      LD   (IX+n), A

This introduces one of the two 16-bit index registers: IX. IX and its sister register, IY, are used to address offsets from memory locations without having to change the value of the register. A one byte, signed offset is set in the code (nn in the HEX code above). This is useful if you are reading or writing several non-continuous bytes from a single offset or multiple offsets in sequence. What this particular instruction does is LoaD the 8-bit value at the memory address (IX+n) with the value in the A register.

All instructions that use the IX register are prefixed with DD. This actually just changes the following instruction to use IX instead of HL, and then reads an additional byte after the Op code if it is in indirect addressing mode (indicated by the use of parentheses in the instruction name). The instruction 77 # LD (HL), A is the same instruction, but using HL instead of an indexing register.

IX is always intended to be used as a 16-bit index register, however, there are several unofficial, undocumented codes that allow using it as two 8-bits registers, HX and HL, just like the regular 8-bit registers H and L.

Length 4 snippet:

HEX Op code   Instruction name
-----------   ----------------
FD 36 nn xx   LD   (IY+n), x

There are very few 4-byte single instructions, all of which are similar in function and use one of the two index registers. This time I am using IY. All IY instructions are prefixed with FD. It is almost identical to the previous example but using a direct value instead of a register. It LoaDs the 8-bit value at the memory address (IY+n) with the value x in the last byte of the instruction. (Normally, this op-code would be written LD (IY+d), n but I am avoiding using d to prevent confusion with the hex digit D.)

Because of the way that DD and FD work, you can actually chain any number of DD and FD bytes together. Only the last one will take effect, wasting both memory and clock cycles. For example, FD FD DD AF will set the current instruction to use IY instead of HL, then IY again, then IX, then ignore them all and execute XOR A (see the length 1 snippet). As you can see, although it produces valid code, it is only useful to prefix instructions with DD or FD if they normally use the HL register (or the H or L registers if you are using undocumented instructions). The CPU automatically resets to using the HL register instead of an index register after each instruction, whether or not an index register actually ended up getting used.

Length 5 snippet:

HEX Op code   Instruction name
-----------   ----------------
AF            XOR  A
80            ADD  A, B
05            DEC  B
20 FC         JR   NZ, -4

There are no single instructions longer than 4 bytes (except for the aforementioned wasteful instructions) so now I need to write mini programs! This snippet calculates the nth triangular number (mod 256 since these registers are 8-bit) from 1 to 256. On entry the B register contains n. On exit the A register contains the result, B contains 0, the Z flag is set, the other flags are corrupted (not guaranteed to stay unchanged, nor to hold useful values, although the value of each flag will be the same after every time this snippet is run; the values are not random and can be predetermined) and all other registers are preserved (unchanged). How can it calculate 256 since the largest 8-bit unsigned value is 255 and why doesn't it calculate 0?

It sets the A register to 0 (see the length 1 snippet), ADDs B to A, storing the result in A then DECrements B. If the value of B is 0 after being decremented, then the Z flag is set. The last instruction Jumps Relative to the current position if the Z flag is not set (Non-Zero), i.e. if B is not 0. FC is treated as a signed value, so it jumps by -4 bytes from the end of the JR NZ, n instruction if the condition is met. So, if B is already 0 upon entry, decrementing it will overflow and set it to 255, causing the snippet to loop 256 times. The largest value it can calculate without overflowing is Tri(22)=253. The result of the next value, Tri(23) is 20 because 276 doesn't fit in an 8-bit number.

  • \$\begingroup\$ I just started page 4 of this question! \$\endgroup\$
    – CJ Dennis
    May 18 '15 at 6:39
  • \$\begingroup\$ if it is compatible to the 8080, how is the Z80 machine code different from 8080 machine code? \$\endgroup\$ Sep 7 '15 at 22:36
  • \$\begingroup\$ @PaŭloEbermann The Z80 extends four unused op-codes. All 8080 op-codes are single byte but the Z80 has multi-byte op-codes starting with CB, DD, ED & FD. A lot of these are used to address registers that don't exist in the 8080. \$\endgroup\$
    – CJ Dennis
    Sep 14 '15 at 13:33



beeswax is a self-modifying 2D esoteric programming language created by Manuel Lohmann, based on a 2-dimensional hexagonal grid. Every cell in a beeswax program (the honeycomb) has 6 neighbors.

  2 — 1
 / \ / \
3 — β — 0
 \ / \ /
  4 — 5

Actual layout:


Instruction pointers (called bees) travel around on the honeycomb. Bees can pick up values from any location on the honeycomb, or drop values on it, potentially changing its size and content. Every bee carries a stack (local stack/lstack), with a fixed length of 3. Bees can interact with a global stack (gstack) of unlimited length that’s accessible by all bees. The gstack only allows basic stack operations like rotating up, down (similar to how Piet handles the stack) and pushing and popping values on or off the stack. All arithmetic or bitwise manipulation of data has to be done by bees. All values in beeswax are unsigned 64-bit integers.

GitHub repository to a beeswax interpreter written in Julia

All snippets in reverse order:

Length 15 snippet (introducing the print toggle switch)

The good old plain “Hello, World!”

*`Hello, World!

The backtick character ` is a toggle switch to print every character encountered after the switch to STDOUT until a second backtick toggles the output off again or until the bee leaves the honeycomb or the program ends, whichever occurs first.

Length 14 snippet

in the works

Length 13 snippet

in the works

Length 12 snippet II


Another 12 bytes long example. This calculates and outputs the fibonacci sequence, part of my solution to the Fibonacci function or sequence challenge.

Finally a program doing something more useful again.


          lstack     output
      *   [0 0 0]•            create bee
     {                 0      output lstack 1st as integer to STDOUT
    P     [0 0 1]•            increment lstack 1st
   <                      (1) redirect to left
  N                   \n      output newline to STDOUT
 {                     1      output lstack 1st as integer to STDOUT
p                             redirect to lower left
>~        [0 1 0]•            redirect to right, flip lstack 1st and 2nd
  +d      [0 1 1]•            lstack 1st=1st+2nd, redirect to upper right
   <                          redirect to left, loop back to (1)
  N                   \n      utput newline to STDOUT
 {                     1
>~        [0 1 1]•
  +d      [0 1 2]•
  N                   \n
 {                     2
>~+d      [0 2 3]•
  N<                  \n
p{                     3
>~+d      [0 3 5]•
  N<                  \n
p{                     5

This outputs the fibonacci sequence, but only up to the 93rd element, after which 64bit-wraparound causes the sequence to produce wrong values:

12200160415121876738   ← 93rd Fibonacci number, last correct value
1293530146158671551    ← 1st. case of 64-bit overflow/wraparound

Implementing a longer word length is possible, of course. Maybe I can implement such a fibonacci sequence program in one of the next examples.

Length 12 snippet

This is my contribution to the Code that executes only once challenge. You have to save this program in a file named !. This program does not add any new fancy ideas—it is just a slightly modified realization of the idea shown in snippet length 10.



                  lstack                        gstack
_8F+++P        [0x08,0x08,0x21]•
       ]       [0x08,0x08,0x2100000000000000]•                        rotate bits of lstack 1st by lstack 2nd steps to the right
        f1     [0x08,0x08,0x01]•               [0x2100000000000000]•  push lstack 1st on gstack, set lstack 1st to 1
          Fw   [0x01,0x01,0x01]•                                      write file named "!" (Char(0x21)) with content 0x00 (1 byte).

So, during execution the program overwrites its own file, so it can’t be executed again.

Length 11 snippet (clear screen using ANSI escape sequence)


This is my beeswax example for the task Terminal control—Clear the sreen on rosettacode, which can be found here.

• marks top of stack
_            [0 0 0]•    create bee
 3           [0 0 3]•    lstack 1st=1
  F          [3 3 3]•    all lstack = 1st
   .         [3 3 9]•    1st=1st*2nd
    .        [3 3 27]•   1st=1st*2nd
     }                   output lstack 1st as char to STDOUT
      `[2J`              output `[2J` to STDOUT

This program uses the ANSI escape sequence ESC[2J, as shown here. 27 is the ASCII code for the control character ESC, [2J is the rest of the ANSI escape sequence to clear the screen.

Length 10 snippet (introducing the file write instruction)


This program writes a file named “Z”, containing one byte of information: 0

             lstack               gstack
_           [0,0,0]•                                 create bee
 Z          [0,0,90]•                                pick up value from relative address lstack(1st,2nd), see length 7 snippet.
  ~         [0,90,0]•                                flip lstack 1st,2nd
   8        [0,90,8]•                                lstack 1st=8
    ~       [0,8,90]•                                flip lstack 1st,2nd
     ]      [0,8,6485183463413514240]•               rotate bits of lstack 1st by lstack 2nd steps to the right.
      f     [0,8,6485..4240]• [6485183463413514240]• push lstack 1st on gstack
       1    [0,8,1]•                                 lstack 1st=1
        F   [1,1,1]•                                 set all lstack to 1st value
         w                                           write file [-,filebytes,namebytes]•

The “magic” becomes obvious if we look at the hex values of the stack contents:

                                   lstack                                     gstack

_           [0x0000000000000000,0x0000000000000000,0x0000000000000000]•
 Z          [0x0000000000000000,0x0000000000000000,0x000000000000005a]•
  ~         [0x0000000000000000,0x000000000000005a,0x0000000000000000]•
   8        [0x0000000000000000,0x000000000000005a,0x0000000000000008]•
    ~       [0x0000000000000000,0x0000000000000008,0x000000000000005a]•
     ]      [0x0000000000000000,0x0000000000000008,0x5a00000000000000]•
      f     [0x0000000000000000,0x0000000000000008,0x5a00000000000000]• [0x5a00000000000000]•
       1    [0x0000000000000000,0x0000000000000008,0x0000000000000001]•
        F   [0x0000000000000001,0x0000000000000001,0x0000000000000001]•                                 

At instruction w lstack is [1,1,1]•. This means, lstack 1st bytes (1 byte) of gstack are used for the file name, and lstack 2nd bytes (1 byte) are used for the file content. The first byte of gstack is 0x5a, or 90 in decimal. This is the ASCII code for the character Z. The next byte is 0x00,which is the file content. So, this program creates a file Z with the content 0x00.

Length 9 snippet in the works...

Length 8 snippet II (truth machine, introducing all conditional operators)

My solution to the challenge Implement a Truth Machine. My full explanation can be found there.

 _T> "{'j

It’s not a real showcase without a truth machine, right? ;) This example also showcases two different conditional jump instructions that are working hand in hand in their functionality.

If lstack is [0,0,0]• (the user entered 0) then the bee only visits the instructions:

_T> "{'

and jumps outside the honeycomb, which terminates the program after printing out one 0 to STDOUT.

If lstack is [0,0,1]• (the user enters 1) then the case gets more interesting:

_T> " 'j'{"> " 'j'{"> " 'j'{">....

which lets the program output an infinite stream of 1s to STDOUT. Instruction j reflects the direction of the IP horizontally (see the list at the length 4 snippet) to run the check over and over again.

Beeswax has 4 conditional and one unconditional “skip next” instructions:

' skip next instruction if lstack 1st value = 0.

" skip next instruction if lstack 1st value > 0.

K skip next instruction if lstack 1st value = 2nd value.

L skip next instruction if lstack 1st value > 2nd value.

Q skip next instruction unconditionally.

Length 8 snippet (introducing absolute addressing)



_         [0,0,0]•        create bee
 4        [0,0,4]•        lstack 1st=4
  F       [4,4,4]•        lstack=lstack 1st
   (      [4,4,64]•       1st=1st<<2nd (arithmetic shift left)
    @     [64,4,4]•       flip lstack 1st/3rd
     0    [64,4,0]•       lstack 1st=0
      @   [0,4,64]•       flip back
       D                  drop lstack 1st at row,column = lstack 2nd,3rd




The 3 instructions D(drop value at cell), G(get value from cell) and J(jump to cell) use absolute addressing. Beeswax programs use 1-indexed coordinates, the y coordinate pointing “downwards”, with the origin at the upper left corner of the honeycomb. Instruction D has the ability to change the size of the honeycomb by dropping values outside the current honeycomb area. Growth in positive direction (down and right) is only limited by the UInt64 number range, growth in negative direction is only possible if values get dropped to the coordinate (0,n), (n,0) or (0,0). The example above drops the value 64 (ASCII for @) at (row,column)=(4,0) Column 0 is the (imaginary) column right at the left border of the honeycomb. If the honeycomb grows in negative direction, then the origin of the new honeycomb gets reset to the new upper left corner. That means, in the example above, the new origin (1,1) changes to the coordinate left of the _. Negative growth is only possible in steps of 1 because unlike the relative addressing instructions, D does not recognize 2’s complements as negative numbers.

A little word of advice: Don’t try to drop values at too high addresses because you’ll run out of memory very quickly. An area of roughly 11,600x11,600 cells already needs at least 1 GB of memory (if the cells only contain 8-bit values and no multibyte characters).

length 7 snippet (introducing relative addressing)


The program above is not really useful, but it demonstrates how the code manipulation instructions that address cells locally work in beeswax. There are two of these instructions that address cells locally: Y and Z. Instruction Y drops values to a cell that’s addressed relative to the position of Y in the program. Instruction Z picks up a value from a cell that’s addressed relative to the position of the Z instruction. As all values in beeswax are unsigned 64 bit integers, there is a problem. You can’t address any cells at relative addresses lower than (row,column)=(0,0). But bees aren’t stupid, so they figured out how to solve that problem by using the two’s complement of the addresses for the cells in question, meaning cells located at the left or below (the coordinate system of the honeycomb is flipped upside down). The two’s complement of a 64 bit integer n is simply 2^64-n.

The addressing works identical for instruction Y.

At instruction Z in the example, relative address

(0,0) is the cell of the instruction itself, returning the value 90, the ASCII value of Z.

(0,1) returns 125, the ASCII value of }

(0,2) returns 0, the default return value if the relative address is outside the honeycomb.

(0,-1) becomes (0,18446744073709551615) and returns 64, the ASCII value for @, and so on.

Z picks up values at the relative address lstack[column,row,-]• and puts the value that’s found at that address on top of the lstack.

Program flow:

_                            create bee
 T                           read in integer from STDIN (enter column of character to be read)
  "                          skip next instruction if lstack 1st>0
   ;                         terminate program (if user entered 0)
    @                        flip lstack 1st and 3rd values
     Z                       pick up value from cell at lstack[column,row,-]3
      }                      output lstack 1st as char to STDOUT


julia> beeswax("snippet7.bswx")

Program finished!

julia> beeswax("snippet7.bswx")
Program finished!

julia> beeswax("snippet7.bswx")
Program finished!

julia> beeswax("snippet7.bswx")
Program finished!

julia> beeswax("snippet7.bswx")
Program finished!

julia> beeswax("snippet7.bswx")
Program finished!

Length 6 snippet (Introducing lstack I/O)


Introducing new instructions: T and ~

Explanation: ( marks top of stack)


*T      [0,0,a]•     Create bee. Get integer from STDIN, store as lstack 1st value.
  ~     [0,a,0]•     Flip lstack 1st and 2nd values.
   T    [0,a,b]•     Get integer from STDIN, store as lstack 1st value.
    +   [0,a,a+b]•   lstack 1st = lstack 1st + lstack 2nd.
     {  [0,a,a+b]•   Output lstack 1st to STDOUT

This program adds two positive integers given by the user.

There are 4 I/O operators that interact only with the lstack:

T Get integer value from STDIN, store as lstack top value.

, Get character from STDIN, store its value as lstack top value.

{ Output lstack top value as integer to STDOUT.

} Output lstack top value as Character to STDOUT.

Just for convenience, during program execution T and , give different output for the input request, so the user knows what is wanted by the program.

T outputs an i to remind the user that an integer is requested. , outputs a c to remind the user that a character is requested.

The program above looks like this during execution:

julia> beeswax("A+B.bswx")
Program finished!

Length 5 snippet


This program ouputs 387420489 to STDOUT, which is the result of 9^9.

Explanation ( marks top of stack):

step          lstack

_9          [0,0,9]•         Create bee, set lstack top value to 9.
  F         [9,9,9]•         Set all lstack values to the first value. 
   B        [9,9,387420489]• lstack top = top^2nd.
    {       [9,9,387420489]• output lstack top to STDOUT.

In beeswax, the numbers 0...9 set the top of lstack to the appropriate integer value.

F sets all lstack values equal to the topmost value. The other operator setting all lstack values to the same value is z (not used here), which sets all lstack values to 0.

This is the first example that uses an arithmetic operator, B, which raises lstack 1st to the power of lstack 2nd value.

Length 4 snippet (Introducing redirection and reflection instructions)


This program outputs an infinite string of zeros.

time      state  output

tick 0:    >_{j
tick 1:    >α{j         _ creates two bees:
                        the first (α) moving right.
                        the second (β) moving left.
tick 2:    β_αj    0    α executes { and outputs its topmost lstack value to STDOUT.
                        β gets redirected to move to the right.
tick 3:    >β{α         α arrives at j, gets mirrored back to the left.
                        β moves to the right, ignoring the _ instruction.
tick 4:    >_αj    00   α and β arrive at the { instruction,
                        both output their top lstack value to SDTOUT, first α, then β.
tick 5:    >α{β         α moves on, β gets reflected.
tick 6:    α_βj    0    α gets redirected to the right
                        β outputs top lstack value to STDOUT.
tick 7:    >α{j         α and β arrive at _ and move on.
                        This state is identical to the state at tick 1.
tick 8:    β_αj    0    Identical to state at tick 2.
  .          .     .                   .
  .          .     .                   .
  .          .     .                   .

beeswax has 6 direct redirection instructions: < b d > q p, redirecting to the left, upper left, upper right, right, lower right and lower left, respectively, as shown in the diagram below (α showing the bee, the numbers the direction):

  b   d
   2 1 
< 3 α 0 >
   4 5 
  p   q

Indirect redirections

Here is a table with all mirroring instructions and their resulting reflected direction.

a and x turn the direction one step clockwise and counterclockwise.

O reflects all directions in the opposite direction.

s,t,u reflect along the main axes \(2-5),/(1-4),(0-3).

j,k,l reflect along the half axes |(between 1-4 and 2-5),/(between 0-3 and 1-4),\(between 0-3 and 2-5).

║incoming  a  x  s  t  u  j  k  l  O ║
║   0      1  5  4  2  0  3  1  5  3 ║
║   1      2  0  3  1  5  2  0  4  2 ║
║   2      3  1  2  0  4  1  5  3  1 ║
║   3      4  2  1  5  3  0  4  2  0 ║
║   4      5  3  0  4  2  5  3  1  5 ║
║   5      0  4  5  3  1  4  2  0  4 ║

Length 3 snippet

Cat program.


Introducing two new instructions:

, reads a character from STDIN and pushes its value on top of lstack.

} returns lstack top value as character to STDOUT.

Length 2 snippet


Introducing the { instruction, which outputs the integer value of the top of the lstack to STDOUT. The lstacks of all created IPs/bees are initialized to [0,0,0] at program start, so this program just ouputs 0 to STDOUT.

Length 1 snippet

The shortest valid beeswax program contains at least 1 of 4 instructions to create bees at the start of the program.

A program only containing one of these instructions does not accomplish anything; the bees get destroyed as soon as they leave the honeycomb. A program that loses all its bees during runtime gets automatically terminated.

  • * creates 6 bees, each moving in one of the 6 possible directions in the following order of creation: 0, 1, 2, 3, 4, 5.

  • \ creates 2 bees in the following order: first bee moving to the upper left (dir. 2), second bee moving to the lower right (dir. 5).

  • / creates 2 bees in the following order: first bee moving to the upper right (dir. 1), second bee moving to the lower left (dir. 4).

  • _ creates 2 bees in the following order: first bee moving to the right(dir. 0), second bee moving to the left (dir. 3).

During program initialization the honeycomb is scanned for these 4 instructions column by column, starting in the upper left corner and ending in the lower right corner of the honeycomb.

A beeswax program may contain an arbitrary amount of these 4 instructions. All created bees are pushed on an IP stack, so the first bee executing code after initialization is the last bee that got pushed onto the IP stack. After initialization, the creation instructions have no effect on program execution anymore and get ignored by the bees if they encounter these instructions.

Length 0 snippet

Invalid program. Beeswax demands at least one instruction for IP creation, no matter how large the program is. The interpreter stops with an error message.

julia> beeswax("invalid program.bswx")
ERROR: No starting point found. Not a valid beeswax program.


Length 16 snippet


Like the length 10 snippet originally was, this snippet is hidden until somebody finds the easter egg.

In this commit, I introduced an easter egg. If you input the correct 16-byte code as an Actually program, something special will happen!

Length 15 snippet


Try it online!

This snippet showcases two new features of Actually:

  • The binary map operator : it works like , but maps a binary function over the top two stack elements, instead of mapping a unary function over the top element.
  • The cumulative sum function σ: it takes a list as input, and outputs a list where each element is the sum of the first n elements of the input list.

The program outputs the cumulative sums of [x**x for x in [1,2,3,4,5]]. The equivalent Python code would be [1**1,1**1+2**2,1**1+2**2+3**3,1**1+2**2+3**3+4**4,1**1+2**2+3**3+4**4+5**5].

Length 14 snippet


This snippet sorts the input list using bogosort and prints out each value in ascending order, separated by newlines.

Cool things in this snippet:

  • Implicit input: because there are no input commands (,, , , or ) in the code, Actually reads all input, parses it, and pushes it before beginning evaluation of the code.
  • The command: it's a shortcut for the map (M) command. It takes the next command (. in the above snippet) and maps it over the list on top of the stack. ♂. is functionally equivalent to the following (and 2 bytes shorter!):

Length 13 snippet


This snippet shows off a lot of new things. In no particular order:

  • :12345678: improved numeric parsing. Rather than needing to be wrapped in :s, numerics merely need to be prefixed with one, and are parsed as the longest string following the : consisting only of characters in 0123456789+-.ij.
  • : new function (gcd reduce). In this form, it pops two integer values off the top of the stack, and pushes them divided by their gcd.
  • : dingbats for characters 0x01 - 0x1F. No more typing those pesky invisible or formatting-ruining ASCII control codes.

Length 12 snippet


Now that Seriously v2.0 (codename Actually) has been released, it's time to start showing off some nifty features I've added. This snippet shows off nested lists - something that Seriously was lacking because I didn't take the time to write a good parser when I created it. This pushes [[1, 2], [3, 4]] to the stack.

But wait, it's missing the ending bracket! Actually, it isn't. It's implied at EOF. However, the inner list(s) still need their ending brackets, even if the ending brackets are at the end of the source code. This may be changed soon.

Length 11 snippet

Note: this is defunct as of now, due to the Heroku site being disabled. No worries though, a similar easter egg will be added into the actual Python interpreter soon.


A newline at the end makes this 11. This is the infamous Konami code - "up up down down left right left right b a" (pressing enter to confirm the code, like start in Contra). Entering this in the online interpreter, using the arrow keys for the directional inputs, will result in a fun little easter egg - the second easter egg I added.

Length 10 snippet


I added two easter eggs to the Seriously interpreter recently. The first one (from this commit) involves doing something special when your code starts with a certain 10 characters. However, I don't want to spoil the secret, so until somebody figures it out, the above code will just be 10 question marks (which is not the secret).

Since I've revealed the original secret in chat, I might as well reveal it here too.

In v1, back before I removed the easter egg, if your code started with ^^vv<><>ba, the rest of the code would get exec'd (run as Python code).

The ? character will eventually be used as a prefix for some two-byte commands, once the single-byte command table fills up. In addition, once I get it working, ?? will be a comment delimiter.

Update: This secret was causing the interpreter to misbehave, so it has been removed for now. It will come back later, once I can make sure it doesn't break things again.

Length 7 snippet


This snippet prints a list of the primes that are less than or equal to the input value.

 ,    push input (indented one extra space here so that the below character doesn't hide it)
▓    pop a: push pi(a) (# of primes less than or equal to a)
r    pop a: push range(0, a) ([0,...,a-1])
`P`  define a function that executes P (pop a: push the ath zero-indexed prime)
M    pop a function f and a list l, apply f to each element of l

Seriously is seriously powerful and terse when it comes to math. I refuse to apologize for the terrible pun.

Length 6 snippet


This snippet showcases the mathematical constant builtins:

pushes π.

ï pushes i, the imaginary unit.

* multiplies the top two values.

pushes e.

^ pops a and b, and pushes pow(a,b).

φ pushes φ, the golden ratio.



This snippet demonstrates Euler's Identity, one of the most important identities in complex analysis: e^(i*π) = -1. The output value isn't quite -1 due to floating-point precision issues and rounding errors, but it's very close. It also outputs φ because I needed a 6th character and I wanted to show off all of the math constants.

Length 5 snippet


Complex number support! I worked a long time on getting this functioning, because Python 2 (the language Seriously is implemented in) does annoying things involving complex numbers.

: is the numeric delimiter - everything between it and the next : (or, in this case, EOF - hooray, more implied delimiters) is interpreted as a numeric value and pushed. If it can't be interpreted as a numeric value, 0 is pushed instead, following the tenet of No Errors.

Length 4 snippet


a: invert the stack

s: pop a: push sgn(a)

d: pop [a]: dequeue a value b from [a], push [a],b

f: pop a: push the index of a in the Fibonacci sequence, or -1 if a is not a Fibonacci number.

Pretty simple, right? Wait... There's nothing on the stack! How is this program supposed to work?

In Seriously, one of the fundamental design tenets was that there are no errors. If a command does not get an appropriate value from the stack, it does not throw an error. Instead, it restores the stack and quietly exits. All of these commands are NOPs when the stack is empty.

Length 3 snippet


This reads in 2 values and adds them (for whatever adding means for the two values). If you pass in two ints, like 5 and 3, the result will be 8. If you input two strings like "foo" and "bar", they are concatenated to form "barfoo" (reversed because they are appended in the order they appear on the stack). If you input two lists, the result will be appending the second to the first: [1,2,3][3,4,5]+ -> [3,4,5,1,2,3]. Adding functions results in their code being appended. Whatever the result, it will be printed to STDOUT.

...wait, why is it printed to STDOUT? There's no . in that snippet! Or is there? When a Seriously program terminates, each value on the stack is popped and printed - there's no need for an explicit . or ü at the end of a program. This is just another feature that saves those ever-precious bytes.

Length 2 snippet


This is an infinite loop. 1 pushes the integer 1 onto the stack, and W is a loop delimiter - the code inside the loop (which is nothing) executes while the value on top of the stack (which is peeked, not popped) is a truthy value (not 0, '', [], or an empty function). This snippet shows off one of my favorite features in Seriously: like TI-BASIC, closing delimiters are not needed at the end of programs; they are implicitly present at EOF.

Length 1 snippet


This prints Hello, World! to STDOUT if the stack is empty.


Seriously got its name from this challenge.

  • \$\begingroup\$ Is the secret easter egg code: Seriously?? Just a random guess. \$\endgroup\$ Nov 20 '15 at 10:29
  • \$\begingroup\$ @DJgamer98 Try it and find out :) \$\endgroup\$
    – user45941
    Nov 20 '15 at 22:44
  • \$\begingroup\$ -1 interpreter doesnt exist \$\endgroup\$ Apr 7 '16 at 0:10
  • \$\begingroup\$ @CatsAreFluffy Oh yeah I need to add the Easter egg into the language proper since I killed off the heroku app. Watch this space for more stuff once I finish the first release of v2. \$\endgroup\$
    – user45941
    Apr 7 '16 at 2:38
  • \$\begingroup\$ @CatsAreFluffy What do you mean an interpreter doesn't exist? seriously.tryitonline.net \$\endgroup\$
    – mbomb007
    Apr 20 '16 at 16:00


TeX was the first language to get its own StackExchange site.

(Note that we will show examples in plain TeX mostly; if any example is to be compiled using LaTeX, it will be clearly stated.)

10 cuff\/link

TeX works well with ligatures such as ff, fl, ffl or fi by default, i.e., it takes the correct ligature glyph from the font automatically. This is in general welcome of course, however, in some cases, it is frowned upon, such as in compound words. Compare the following two renderings of the word cufflink, the first one proper (ligature broken on the compound word boundary) and the second one improper (ligature crossing the compound word boundary). The first one is achieved by adding \/ in the code in the correct place.

enter image description here

9 \badness0

Yes, in TeX, you can define how "bad" things are :-) Well, actually, badness inserted in a paragraph of text says how bad it is if a linebreak appeared at the specific place. Some things insert their own badnesses; for instance, it is worse to hyphenate words than not to, and the non-breaking space has badness of 10000, which is, in a sense, the infinite badness in TeX's eyes. Here, we set the badness to zero. We also see that assignments in plain TeX are done by concatenating the register (\badness here) and the value; optionally we can place the equals sign in between.

Actually, the concept of penalties (badnesses) is crucial for TeX; it's a typographic system and beauty is one of the goals, and Knuth designed TeX so that only deterministic algorithms are used to break paragraphs into lines and lines into pages, to ensure at least reasonable stability.

8 \def\x{}

Simple definition. This defines a macro ("control sequence" in proper words) which does not take an argument and expands to ... well ... nothing :) (Do not be confused: "nothing" is not "relax", they substantially different.)

7 $$a+b$$ or \[a+b\]

Two snippets that somehow produce the same output, it's a displayed equation showing simple

a + b

(just centred of course). The first is the correct thing to do in plain TeX. If only people knew how wrong it is in LaTeX, where the second one should be used!

6 \relax

TeX is one of the languages that have its own "do nothing" action. However, \relax is more than just that, and this is related to the fact that it is an expansion language: All macros are expanded, and in some contexts, executed. The power of \relax is that it is executed to nothing, but it cannot be expanded, i.e., it survives any expansion unmodified. This in turn is one of the strenghts (and threats at the same time, especially for newcomers) of TeX.

5 X\bye

A minimal document that compiles producing an output; we get a page with a 10-point "X" at the top and a centred page number "1" at the bottom. ... "X," said Tom, and added, leaving: "Bye!"

4 \bye

When you say "bye" to TeX, it finishes the document; namely it closes the current paragraph if any is open, ships out the last page, and ends. Without this command, no document can be successfully produced.

3 $a$

Prints the mathematical symbol "a", that can stand for instance for a variable, function or a constant. Without the dollars, it would be the text symbol "a"; it is necessary to distinguish these two!

2 <endline><endline>

Two consecutive ends of line finish a paragraph. (One end of line behaves like a space.)

1 %

The percent sign starts a comment; the comment runs until the end of line, and eats the end of line together with leading whitespace on the next line.

  • \$\begingroup\$ You have 6 more facts to add... :) \$\endgroup\$
    – Alan Munn
    Jun 24 '16 at 23:15


Perl is a general-purpose, dynamic programming language. It was created by Larry Wall in 1987 and is still widely used today. Perl is not an acronym, but there are a couple of backronyms in place, such as "Pathologically Eclectic Rubbish Lister" "Practical Extraction and Report Language".
Snippet Length 1
In Perl, semicolons mark the end of a line. Because empty lines are ignored, this program simply exits without doing anything.
Snippet Length 2
1 is a true value in Perl. In Perl modules, the code has to end with a true value, usually this (or sometimes something rather silly.)
Snippet Length 3
You're probably wondering: "What's that funky symbol doing there?" Well, in Perl, the & symbol marks the beginning of a subroutine (also known as a function). This executes the subroutine a and quits.
Snippet Length 4
Any positive non-zero number is true in Perl, as well as almost any non-empty string. ('0' is false.) Since 1 + 1 = 2, and 2 is a positive number, this works just like the 1; snippet.
Length 5
This assigns a scalar variable in Perl. See that $? That's what makes it a scalar. This assigns $_ with the value 3.
Length 6
There's something special about $_: it's Perl's default variable. Most times, if an argument is not given, it falls back to $_. This prints 3, assuming you set a variable like in the length 5 snippet. Length 7
What is THAT? Did I just take letters and add slashes? No, this is the substitution operator. What it does it is takes a little b and replaces it with a big B. The /g is for global, which tells it to do this for all matches. Of course, it's doing this on $_, Perl's default variable, but I'll show you how to do it properly later.
Length 8
This defines an array with the items 3 and 4 in it. An @ makes it an array, just like $ makes it a scalar. Note that @_ is not Perl's default array.
Length 9
The if conditional works as you would expect it to in other languages. It checks if the statement inside the parentheses is true, and if it is, executes the code in the brackets (in this case, none.) Note that the brackets do not have to end with a semicolon.
Length 10
$o=`cat A`
In Perl, backticks can be used to get the output of a command. Here, it gets the contents of the file "A" (from the cat command.)

  • \$\begingroup\$ Length 8 is incorrect. It gives you an array with one array ref in it. \$\endgroup\$ Sep 7 '15 at 23:55
  • \$\begingroup\$ @skibrianski Thanks for pointing that out, it's fixed now. \$\endgroup\$ Sep 8 '15 at 17:23


Fishing is a 2-D programming language created by OriginalOldMan in 2013.


This language is based off of "fish" that a "fisherman" catches as he walks along a "dock." Fishing implements a memory tape similar to that of Brainfuck.

Note: Since Fishing is very byte-inefficient and that programs with odd byte count are impossible, the length refers to the number of characters used to define the dock. The dock begins after the initial direction walking, direction casting, and casting length of 1 have been set.

Dock Length 0


This sets the fisherman to cast his line down by 1 space. The direction the fisherman casts is determined by v, >, <, and ^. The length of the line being casted must be a positive integer to work. It is controlled by + and -. By default, the fisherman begins walking east. The commands for the direction the fisherman walks are [ to go east, ] to go west, | to go north, and _ to go south.

Dock Length 1


This sets the first cell on the tape equal to the user input. Note that the fisherman is casting to the east.

Dock Length 2


This is cat. The user input will be printed with a trailing newline.

Dock Length 3


This assigns the string A to the first cell on the tape.

When the fisherman catches a tick, the string between the ticks is assigned to the first cell (and can be printed with P or N).

Dock Length 4


Look! Our first example of the fisherman not walking east for the entire program. Like in the snippet with dock length 2, the fisherman will cast west. However, he will also be walking south. Here, the command to walk south must occur after the fisherman receives the information that he is casting to the right by 1, or there will be an error.

In order to have a manipulatable number on the tape, the number must be entered as a string and later be converted into a decimal with n.

Dock Length 5


The string ab is put on the tape, and r is used to reverse it. Note that r cannot reverse a number if the command n has been used on the number. Thus, r will work for the fish `12`r but not for `12`nr.

After the above program, the tape contains the string ba.

Dock Length 6

    a `N

Here, we see a couple modifications to the dock itself. The direction of casting is changed from south to north by ^. We also see D for the first time. D does not have any function but to keep the fisherman walking on the dock. The fisherman does not cast or change direction. The only function of D is for space.

The above program prints a with a trailing newline.

Dock Length 7


Fishing works through a series of cells on a tape. It's about time we see implementation of multiple cells. The above code assigns 4 to the first cell, moves to the right by one cell with { (moving to the left is done with }), and assigns 1 to the second cell.

Dock Length 8


We should recognize n and N from before, but S is new. S squares the value in the current cell. The above program will print 34225, which is equal to 185^2.

Dock Length 9


l is an interesting fish. It finds the length of the current cell and adds it to the end of the tape. The above code will print the length of the string 2015, which is 4.

Dock Length 10


One of the cool things about Fishing is that it is really easy to obfuscate messages, such as above or in this obfuscated Hello, World!. The fisherman does not need to catch all of the fish in the program, as seen above. Any characters in the pond that are not caught are simply ignored.

The above program puts eridan on the tape. The er in personally, the ida in unliquidated, and the n in disjunction are used. Another grid that would put eridan on the tape is here.


Dock Length 12


We can finally have non-arbitrary interactions with other cells on the tape without the value of the second cell depending on the value of the first. We achieve this with a, which adds the value of the cell to the right on the tape to the current cell on the tape. The above will set the value of the first cell to the integer 9, set the value of the second cell to the integer 8, then replace the first cell with 17, and print it.

Dock Length 16

  `Hello, World!`P

There it is: Hello, World! This should be the shortest version there is.

Unfortunately, since Fishing isn't that high-tech of a language, my answer will stop here. Thank you all very much for upvoting!

  • 2
    \$\begingroup\$ Heh, of course you'd do a fish-themed language, \$\endgroup\$
    – Deusovi
    Oct 27 '15 at 18:28
  • \$\begingroup\$ @Deusovi I'm going to be perfectly honest here - I never realized the irony of that. \$\endgroup\$
    – Arcturus
    Oct 27 '15 at 18:31
  • \$\begingroup\$ My goal for this answer is just to get to 16 so I can post Hello, World! \$\endgroup\$
    – Arcturus
    Feb 22 '16 at 15:50
  • \$\begingroup\$ @ANerd-I 2 more to go 'till 16... \$\endgroup\$ Apr 8 '16 at 5:24
  • \$\begingroup\$ @ANerd-I You're 14 total votes now. \$\endgroup\$ May 30 '16 at 7:00


Unlike many other languages, Tcl has no reserved words, the control structures are just "normal" commands.

2 chars


Empty string literal.

5 chars


Used as index, means the second last element.

6 chars

if 0 ?

Just a comment. Can span multiple lines.

  • 1
    \$\begingroup\$ I think you should add the {}, end-1. \$\endgroup\$
    – jimmy23013
    Jan 24 '15 at 9:07


Factoid: The first Fortran (then called FORTRAN) compiler was created at IBM in 1957. Programs were originally submitted on punch cards.

Length 7:

"What am I looking at?" one might wonder. Why, that's seven spaces, of course! "Okay, why seven spaces? That's a dumb choice for a snippet." Perhaps, but it illustrates an important concept in early versions of Fortran: all code other than labeled lines and comments had to begin on column 7.

Here is an example of FORTRAN 77 code that exemplifies this and a couple other concepts we've seen thus far:

C      This is going to be so cool, guys
C      We gonna compute so many GCDs, just you wait
       PROGRAM GCD(A, B)
         N = A
         M = B
100      IF (M .NE. 0) THEN
           I = N
           N = M
           M = MOD(I, M)
           GOTO 100
         END IF
         GCD = N

Note the GOTO within the loop. It's acting as a while loop, which was eventually implemented as do while in Fortran 90, but was unavailable in FORTRAN 77.

Length 6:


Early versions of Fortran had no character type. To manipulate strings, one had to use Hollerith constants, which themselves are typeless but can be stored in numeric variables. Hollerith constants begin with the length of the string in bytes, then H, then the string contents.

In this example we have 12HPCG, which allocates 12 bytes for the string PCG. Since we've allocated more than we've provided, the actual string that gets used is "PCG ". In such situations, the provided string is left-justified within the field and padded with spaces to fill the allocated length.

Length 5:


Fine grain parallelism, anyone? You can invoke OpenMP using the directive !$omp, assuming you've compiled the program with OpenMP enabled. If you haven't, notice how the directive begins with an exclamation point. As we saw in snippet 4 below, this marks a comment. So if OpenMP isn't enabled, the compiler just sees this as a comment.

One of the most common uses of OpenMP in Fortran is the parallel do loop. A toy example:

!$omp parallel do
do i = 1, n
    y(i) = 10*x(i) + 1
end do
!$omp end parallel do

This will spawn up to omp_get_num_threads() threads, each performing a single iteration of the loop in parallel.

Length 4:


Fortran has derived data types! I'm not sure how long that's been available, but it's at least been present since Fortran 95. Types are defined like so:

type dog
    character(10) :: breed
    real :: age
end type dog

You can then declare, assign, and access variables of this type.

! Declare Lucy as a dog
type(dog) :: Lucy

! Tell me about Lucy
Lucy = dog('Newfie', 8.1)

! What's Lucy's breed?
her_breed = Lucy%breed

Note the exclamation points: that's the more modern of the two ways to include a comment in Fortran. The other is to put C in the first column of the line.

Length 3:


Of course end is boring. However, if you're writing a program in Fortran, you'll find yourself writing end all over the place: end do, end if, end program, end function, end subroutine, etc. So aspiring Fortran users beware: the end is entirely inescapable.

Length 2:


You'll probably find it difficult to get by without declaring a few variables. That's where the double colon comes in!

Say you're writing a subroutine that takes an argument a. You can tell Fortran a bit about a by saying, for example, real(8), intent(in), parameter :: a. This declares a to be a fixed 8-byte real input that won't be returned. Note the colons separating the attributes from the variable. Now if you were to also declare a variable b that isn't an argument, it's just a plain old real, you can omit the colons: real(8) b. The colons are only required if you're specifying a type and attributes.

Length 1:


Who doesn't love a good GO TO statement? You can make a labeled line by putting a number in the first column. If you have a labeled line, you can GO TO that line using GO TO 1.

  • 2
    \$\begingroup\$ Shame I didn't see this or think of it sooner. I love fortran. \$\endgroup\$
    – krs013
    Mar 11 '15 at 4:20


I've been wanting to put this up for ages. Here we go...


Vitsy is a stack-based 1D programming language with a stack composed of stacks composed of doubles. At any point, the program stack may look like this:

4 8 9      As you can see, each sub-stack may have its own unique length.
8 3 2
9 6 4      Items from the current stack will always be pulled from the top, unless 
3   3      otherwise specified by the user.

These would technically be doubles, but, hey, it's a representation.

Length 1 Snippet:


The shortest stack overflow error you'll ever see.

Basically, in Vitsy, the [ represents "start while loop". While in a while loop, the program will wrap around the line - which means it starts another while loop, which wraps around the line and starts another while...

You get it.

Length 2 Snippet:


Prints the number 78 to STDOUT.

The character " captures any characters following it as a string and pushes it to the stack. Whenever Vitsy is capturing text, it wraps around the line. Therefore, N is pushed to the stack. Then, the character N prints the top item of the stack to STDOUT. ASCII Character 78 is N, therefore, 78 is printed to STDOUT.

Length 3 Snippet

Length 3... in characters.


Since Vitsy reads unknown characters as NOPs and can read character values of UTF-8, the character ߟ translates to the number 2015.

Happy late welcome to 2015, everybody.

Length 4 Snippet


Just in case you ever want to reverse an input, this will grab the input a character at a time, reversing the string in the process.

Length 5 Snippet


This code will always error unless the number 1 is input.

m tells the program to go to a line specified by the top item of the stack. If the number is 0, it'll duplicate the top item and go to the 0th line, the line with the m in it. This will throw the standard StackOverflowException. If it's 1, it'll go to the first line (0), push 0 to the stack, go back to where it left off (N), and push the top item of the stack to STDOUT as a number (0). If it's greater than one, or less than 0, it'll throw an ArrayOutOfBoundsException, because it doesn't know where to look for the specified line.

Length 6 Snippet

The standard quine is simply:

'      Capture all items as string until encountering another one
       of itself. If it does not find it before the end of the 
       line, it will loop around the line back to the start,
       which makes this capture all of the instructions as a string.
 r     Reverse the current stack
  d3*  Get the ASCII number of '
     Z Print everything in the stack out as a character.

I love how short this is, and it was totally unintentional. :D

Length 7 Snippet


This program will print out a single zero if the number input is not prime, and infinite 0s if it is prime. Basically, it tests if a number is prime. If it is, it skips the <, which forces a backward loop (which will always find 0 because 1, the truthy for the prime number test, is not prime.

Length 8 Snippet


I just realized I haven't introduced stack features. ¯\_(ツ)_/¯

Vitsy also has stack manipulators - in this example, I grab input as an integer implicitly, get a random decimal in the range [0,20) and generate that number (when looping, we use the truncated integer as the repeat count) many times. Note that this will be in the range [1, 20], as there is already a stack.

Length 9 Snippet:

;use a

So, let's say that you want to use another program (called "a") in your program. So what do you do?

You import it with ;use. Then, you get the 0th index of the ;use declaration's 0th line of code (00k). Very fancy classes. This will be the basis in which I will create libraries for Vitsy. (Note that this is now ;u - the declarations were changed to only the first letter as of a later update)

Length 10 Snippet:

What's the date again?


Vitsy doesn't have it's own way of getting the date - but it does have JavaScript eval worked into the code. That means that I can get the date string that JavaScript returns by pushing Date() to the stack, then eval with JS (n), then outputting the entire stack (Z). Fun, huh?

Length 11 Snippet

It's getting harder to make these. D:

iG' ystiv',

Well, this code is not fun. If you have Vitsy saved as a system command (like I do), you can have problems like this. Basically, I grab the filename and push it to the stack with iG (push -1, get that index of class name), then I push 'vitsy ' behind it. Then I execute that in a shell.


Forkbomb = sad

Length 14 Snippet


What I'm doing here is moving a prompted input number of items to a following stack. This would likely be used in a non-runnable class like so:


And called like so:

;u something.vt


I grab the top item of the stack (my number of items to move), make a new stack, push that number back in and repeat everything in the loop brackets that many times. y1- signifies the number of stacks currently in play minus one, so y1-\? goes to the stack previous of the one you're currently in (because I'm an idiot and never implemented going backwards - but don't worry, it'll be here soon).

Length 15 Snippet - Fibonacci!

11[XD{+DN' 'O1]

This outputs the fibonacci sequence, separated by spaces, to STDOUT infinitely.

Interestingly enough, while making this code the first time, I realized that separating by spaces (with a small delay between each output) caused parabolas to appear in the output. Go figure.

  • \$\begingroup\$ How come Date() is backwards in length 10? \$\endgroup\$
    – GamrCorps
    Dec 9 '15 at 14:03
  • \$\begingroup\$ Vitsy is a top access only stack. When I do eval, it grabs it in reverse order of how I put it into the stack. That means that )(etaD is read as Date() by eval. @GamrCorps \$\endgroup\$ Dec 9 '15 at 14:08
  • \$\begingroup\$ Ah, I see. Thanks. \$\endgroup\$
    – GamrCorps
    Dec 9 '15 at 14:12


Weird how nobody's done this one yet, as it's quite popular on this site.


Written and released in 2007, GolfScript is probably the first esoteric programming language invented for the purpose of code golf. Since then, it's inspired CJam, Pyth, Rebmu, gs2, and maybe others.

1 character


GolfScript is a stack-based language, and all of standard input is pushed onto the stack when the program starts. The , command pops a value, and, if it is an array or string, pushes back its length. At the end of the program, every value on the stack is printed, bottom-to-top. Thus, this program calculates the length of whatever input you pass it, like wc -c! Our 1-character program is already a useful tool.

2 characters


This program prints the bitwise NOT of a number given on standard input. For example, when you pass it a file containing 5, it will print -6.

This, of course, showcases a trick GolfScript uses to cut down code size: not only does it assign operations to lots of single ASCII characters, it also assigns multiple meanings to each character depending on the type(s) of the value(s) popped.

For example, ~ on strings is eval(), which is the simplest way to read a number from a string in GolfScript. It pops a string and executes it as code, pushing back an integer in our case. Applying ~ again to this integer, it does something very different: namely, compute the bitwise NOT of the given value and push it back.

3 characters


This program reverses standard input. -1 pushes -1 to the stack, and <string> <int> % corresponds to Python's string[::n] behavior: it steps through characters from the string from one end to another with the given step size.

4 characters


This is the idiomatic GolfScript to write sum(), i.e., the sum of values in an array (or string, which is just a special kind of array). It will sum together the ASCII values in the standard input string, or whichever list is on top of the stack. {+} is a block, representing some GolfScript code (+), and it is folded * over its bottom argument. This has a precise meaning:

    [a b c d e] {∘} *

==  a b ∘ c ∘ d ∘ e ∘

i.e., it is a left fold with the first element of the list as the initial value.

5 characters


Ironically, GolfScript has commands that are longer than one character, for... no reason at all. (Well, when I asked Darren about it in an email, a long time ago, he said he simply didn't want the language to be frustrating to program in, and keywords like and, or and base are probably easier to remember than single characters!)

The base command takes a positive base n as an argument, and performs a conversion between lists of base-n digits and integer values. Applying 2base to a list like [1 1 0] will yield 6, and vice versa.

6 characters


n pushes a newline to the stack, and / and * are the split/join commands to convert between lists and strings. So, this first splits the input string into lines, does something to that list of lines, and joins it back into one long string with newline characters in it.

But what does it do? . is a stack operation that duplicates the top element on the stack, which is now our list of lines, twice. & will pop these two lists and compute their set intersection. That's sort of weird; we're computing L ∩ L, which set theory tells us is just L. This is a little GolfScript trick, though (and it also works in CJam): the implementation simply calls Ruby's &, which does the same, and has the additional result of removing duplicates from the list, while preserving their order.

So we have a 6-character program to remove duplicate lines from standard input.

7 characters


[list] [block] $ is "sort by", which is a very powerful tool: it will sort the array by whatever function the block represents. Here, , is "length", and the snippet expects a list of strings on top of the stack. It will sort the list by length, and then extract the final element (-1= indexes the list) to find the longest string in the list.

8 characters


The shortest GolfScript quine. Note that e.g. 1 isn’t a real quine: that prints 1\n! How does this all make sense?

At the end of program execution, GolfScript wraps the current stack in a GArray and evaluates puts, which is by default defined as print n print.

What we do, then, is assign the string ":n`" to n, and then inspect (`) it to push "\":n`\"" on the stack. The implicit printing of n that happens at the end of our program is now exactly what we need to finish our quine!

9 characters


GolfScript is implemented in Ruby, and it uses eval to read its string literals. This means you can “statically” call any Ruby code you want! In this case, the size method call is evaluated on "\"#{size}\"" (I’m not sure why) and the result is the string "9". That string is, again, implicitly printed, so this program just outputs its own size: 9.

10 characters


This prints:


First, do is one of GolfScript’s flow control structures: {thing}do in pseudocode is like do { thing } while popStack() is truthy. Our thing is 9(:9.(. That’s push 9, decrement, assign to 9 (yes!), duplicate, decrement.

The assignment to 9 is the tricky bit! Pushing an integer literal isn’t exempt from a variable lookup in GolfScript; when you push 9 for the first time, a variable called 9 gets assigned the value of t.to_i == 9 on the fly. There’s not actually much special about this variable, and as you can see, assigning to it is A-OK.

(This is actually useful: instead of starting with 0:x; and then updating x a lot, you can often just work with 0 itself as a pre-initialized variable.)

As a condition, we have .(: loop until whatever is on the stack, minus one, is falsey, i.e. zero. So we push decrements of 9 until they reach 1, i.e. 8 7 6 5 4 3 2 1. These all get printed after each other without spaces in-between by the implicit wrap-and-print at the end of the program.

  • 1
    \$\begingroup\$ +1 can we have some more? \$\endgroup\$ Jan 14 '16 at 5:55


/// is a minimalist Turing-complete esoteric programming language. The only operation is repeated string substitution, using the syntax /pattern/replacement/.


/// was proved Turing-complete by Ørjan Johansen in 2009, who created an interpreter for the Turing-complete language Bitwise Cyclic Tag.

(from http://esolangs.org/wiki////)

You can test the snippets here, or click their header.

Length 1

There's not much that can be done with one character in this language, so have a unicode snowman.

Length 2


This won't print a newline. A \ in this language means that it'll print the next character, so it'll print a n. \s are used mostly for printing /s, like this: \/.

Length 3


This is an infinite loop that does nothing, and is also the language name. It keeps replacing nothing with nothing.

Length 4


This attempts to replace a snowman with nothing/remove every snowman. Since the entire source code, except the /☃// part, doesn't contain a snowman, it doesn't do anything.

Alternative Length 4

/ //

Unary addition! Put both numbers on the right side of the snippet. (since /// can't take input) Like this: / //00000 000

Length 5


This snippet is important for showing one thing: string substitution doesn't work on anything that comes before the /pattern/replacement/.

If you take a look at snippet length 4, it removes every snowman. But that won't work if there are snowmen before the /pattern/replacement/, so he stays there and get printed.

However, this snippet would remove the snowman, because the snowman comes after the /pattern/replacement/ part: /☃//☃.

Alternative Length 5


This snippet completely breaks the language. It works by removing every /.

Try it here.

Length 6


Remember the second snippet? Instead of writing \n, you use a literal new line.

Because Markdown apparently doesn't like empty lines of code, you have to remove the (newline) part when trying this in Try it online! or any other /// interpreter.

You probably guessed it by now, but I'll explain it anyways. The /\n/☃/ part replaces every newline with a snowman. Since there's a trailing new line in the snippet, it gets replaced by a snowman and printed.

This is probably kinda boring, but don't worry, I have something more interesting planned for the seventh snippet :-)

Length 7


This is an infinite loop. More interesting than the sixth snippet IMO.

When /// finds a /pattern/replacement/, it will keep replacing pattern with replacement until there are no more patterns to be replaced. Therefore, if replacement contains pattern, it will always end up on an infinite loop.

There will always be a snowman to get replaced with a snowman and a badly drawn snowman:


Alternative Length 7

/0 0/ /

Unary subtraction! Put the numbers in this order: largest smallest, like this: /0 0/ /0000000 00000

Length 8


Yay, 8 upvotes! An eight is the number that looks the most like a snowman.

The /☃/\// part replaces every snowman with a /. So you will probably think that if I place a snowman in the code, it'll print a /. Wrong.

Since /s are used for repeated string substitution, you'll have to put a \ before the / (in this case, the ) if you wanna print it.

This may seem obvious, but I forgot it once and spent some minutes trying to find the bug in my code.

Length 9


The /☃/\\\\/ part replaces every snowman with two \ (Since \\ is only one \, \\\\ is actually \\).

There's only one snowman after that, so it gets replaced by the two \.

Finally, the two \ turn into only one \ and that gets printed.

Length 10


If you pay attention, the second replacement is incomplete. The first replacement replaces a snowman with an eight.

The second replacement doesn't do anything, since it's incomplete. Syntax errors don't exist in ///, so nothing happens. If you don't believe me, turn on debug on TIO.

Length 11


I just realized today is 11/11, I'm adding snippet length 11 and this post has 11 upvotes...

I don't think there is anything important left to showcase about this language, /// is very simple. But I'll still try to add more snippets.

This is probably obvious, but replacements can modify other replacements.

The first replacement replaces every snowman with an eight:


This is an infinite loop (/8/8/), since there will always be an eight to be replaced.

Length 12


Making replacements with replacements! /☃/\/8\// replaces with /8/:


As you can see, this is now a replacement. It replaces every 8 after it with B.

A snippet with a ★ means that it requires "input" (place input on the right side of the code) and it won't do anything by itself.

  • 1
    \$\begingroup\$ What did you plan for the 7th snippet? \$\endgroup\$ Sep 23 '16 at 10:12
  • \$\begingroup\$ the alternate fifth doesn't have the backslash \$\endgroup\$ Oct 28 '16 at 22:39
  • \$\begingroup\$ @DestructibleWatermelon fixed \$\endgroup\$
    – acrolith
    Oct 29 '16 at 1:00


Factoid: Pyke is a stack-based golfing language with lots of implicit inputs. It was created to be easily extendable in February 2016. It is a great language to golf in.

1 byte:


Try it here!

This is the shortest semi-infinite loop in Pyke (Pyke has a setting that breaks out of it early turned on by default). It is equivalent to


r has 2 defined functions - goto_start and return. If r is visited in a function macro, it will instead return the current values on the stack.

If an error occurs whilst redoing the code again, it will go back to r and continue onwards.

2 bytes:


Try it here!

The factorial function - not a builtin. Equivalent to

product(range(1, input+1))

Input is implicit in Pyke, whenever input is missing, it loads the next value off the input stack onto the program stack. At the end of the input stack there is an infinite amount of whatever the first item was. Output in Pyke is also implicit. Explicit output can also be used with the newline and p nodes for with and without a trailing newline respectively.

3 bytes:


Try it here!

This actually shows off 3 interesting features:

]   -   [input, input] - Pyke reuses the stack when already used
 U  -  2d_map(^) - Creates a 2d range, effectively an `a*b` grid
  P - pretty_print(^) - Pretty print the values keeping the same padding for every column

4 bytes


Try it here!

This shows off Pyke's for-loops using strings. If the input to a for loop is a string and the output is a list of strings, it automatically concatinates them together. Equivalent to

rtn = []
for i in input:
rtn = "".join(rtn)

5 bytes


Try it here!

This program outputs if the input is a Fibonacci number. It uses the up_to node to generate Fibonacci numbers up to the input and then decides if the input is in that list

      - rtn = []
      - i = 0
#  )  - while rtn[-1] <= input:
 .b   -     rtn.append(nth_fib(i))
      -     i += 1
    { - input in rtn

6 bytes


Try it here!

Pyke has a neat function for clock related queries. The C or 'clock' takes any amount of numbers afterwards and returns a time-related thing for each of them.

  • 6 - months
  • 9 - Months of the year (1 indexed, 0 is "PADDING")
  • 5 - days

The script outputs the day of the current month as well as the name of that month.

C695   - stack = months, month_names, days
    @  - stack = month_names[months], days
     ] - stack = [month_names[months], days]

7 bytes

Finally... We got there, an absolutely minimal 'Hello World' program. Yes that is 7 bytes, in characters it is . d 0x02 0x0973 v


Try it here!

This uses Pyke's built in compression to stick the words 'hello' and 'world' together. . d 0x02 says that there are 2 words to be combined and the other 2 characters say which words to use.

A compressor for Pyke can be found here

8 bytes


Try it here!

This introduces 2 new features: Variable modification and escaping of infinite loops.

The explanation is annotated with python code to show what each character's doing

         - Y = 256
     r   - try:
         -     while True:
 ? Y     -         Y = lambda: v(Y)
  t      -             lambda x: x-1
1   /    -         stack.append(1/^)
         - except:
      "Z -     stack.append("Z")

The ? inplace variable modification node applies the first node to the contents of the second. Eventually Y will equal 0 and the 1/Y section will raise a ZeroDivisionError and will jump out of the infinite while loop.

9 bytes


Try it here!

Takes a list of numbers and outputs the largest even number or 0 if there are no even numbers in the list.

S         -  sorted(input)
 #   )    - filter(V, ^):
  2%!     -  not i%2
      1|  - ^ or 1
        e - if isinstance(^, int): floor_half(^)
          - else: ^[-1]

This overloads the e node which when given a list returns the last element and when given an integer, divides it by 2 and rounds down.

10 bytes


Try it here!

This uses the brand new time types to add 1 hour 30 mins to the current time and drop the date part

C          -   current_time()
        +  -  ^ + V
 y1H30M"   -   time(hours=1, minutes = 30)
         t - time(^)

11 bytes


Try it here!

This shows off two new instructions (There are in fact only two unique ones in the program). These are the repeat V and the print_grid .X functions.

V takes an integer or iterable and repeats the code the length of that iterable or the number of times. It takes the whole stack and when it loops, the current stack is kept and fed as input. If an iterable is passed, it also pushes that iterable at the beginning.

.X is a special function in that it will probably only be used in challenges requiring a strict output format. It takes a string (with optional newlines) and pads it so it is in a grid-like format. It also optionally takes up to 8 characters to pad with:

0: upper (all characters have this as default)

1: topleft (corners if undefined have this)

2: left line

3: right line

4: lower line

5: topright corner

6: bottomright corner

7: bottomleft corner

If no characters are given, it defaults to surrounding the entire thing with spaces. The program can stop defining extra characters by ending with a ".

V           - repeat number of times:
 .X"        -  surround with spaces
    .X-+||" -  surround in a ascii box

12 bytes

Whoever said golfing languages had far to many useless builtins?


Try it here!

Returns the distance Jupiter will be from Earth on the next full moon (in AU). Seriously.

C            -   current_time()
 B           -  full_moon_after(^)
  "Jupiter"@ - distance_to_earth("Jupiter", time=^)

Also works for all the planets in the solar system as well as some artificial satellites such as Voyager 2 and PIONEER 10

13 bytes


Try it here!

We've just gone infinite! Returns an infinite list of all the prime numbers combined with all numbers with 2 prime factors.

~1            -    An infinite list of all the natural numbers, starting from 0.
  #  )        -   filter(^ as i, V)
   _P         -    is_prime(^)
      D3      -  duplicate ^ 3 times
        M*    -   cartesian_product(^ * ^) (Return an infinite list of all numbers with 2 prime factors)
          +   -  ^ + ^^ (Return an infinite list with a semi-sorted transposition of the 2 input ones)
           mP - map(factors, ^) (Return an infinite list of the factors of the 1 and 2 factor numbers)

Infinite lists are effectively Python's generators. At the end of a Pyke program, all infinite lists on the stack are unwound as far as it will go in the time limit available (or none if done offline). Pyke has operators to filter and map nodes to infinite lists as well as combine them in various ways. Infinite lists are a relatively new feature and have been used in several short answers.

14 bytes


Try it here!

Prints out every second in a day. This could be useful for challenges where you have to filter by specific seconds.

y0:0"         - create the time "0:0" (0 hours and 0 minutes)
     w𕆠      -  86400. Takes the ordinate of `𕆠` - 32.
        V     - repeat ^ times: V
         s5   -   increment the seconds by 1
           \n -  print(^)

Both s and l change the amount of time by a predetermined amount. s increases and l decreases.

0 - years

1 - months

2 - days

3 - hours

4 - minutes

5 - seconds

6 - weeks

7 - 4 years

8 - decades

9 - 12 hours

15 bytes


Try it here!

Again another dictionary command. It's up to you to understand what it does


The Lambda Calculus


The lambda calculus (specifically, the untyped lambda calculus) is, according to Wikipedia, "a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution." It was published by mathematician Alonzo Church, of whom Alan Turing was a student, in 1936, and is equivalent to a Turing machine—that is, any problem solvable with an algorithm can be solved with this system.

The lambda calculus consists entirely of functions of one parameter. In its pure form, these functions are unnamed, but for ease of understanding, they are often given names like plus and equals. Most[citation needed] modern languages, including Python, C#, and Java, support these anonymous functions.

Length 1:


The variable x. A variable is the simplest example of a lambda term, or a valid lambda expression. Note that a variable need not have a type (in fact, must not in the untyped lambda calculus, as types do not exist [hence, untyped]).

Length 3:

f x

Application of the function f to the variable x. Note that function application is left-associative, though this can be overridden with use of parentheses.

Length 4:


The identity function! This gives a first look at the form of functions. A lambda function consists of two parts: the parameter (the variable between the first λ [lowercase Greek letter lambda] and the first .), and the return value (everything after the first .). In this example, the parameter, x, is mapped to (guess) x, so the identity function returns whatever value it is fed, be it a number, a Boolean, or a lambda term.

This is an example of an inductive rule of lambda terms: if t is a lambda term and x is a variable, then λx.t is a lambda term. In this example, t is the lambda term x, so this rule makes λx.x a lambda term.

Length 4:


A slightly less interesting example, this is a function of x that returns y regardless of x's value. Feed it 5? It gives y. Feed it λx.y? It gives y. Since y is a variable and therefore a lambda term, this expression is indeed a lambda term.

Length 5:

f x y

This is application of a curried function, the basis of the computational completeness of the lambda calculus. f is here called on x, returning f(x), a function (this is called partial application—though f takes two parameters, one can create a new function by passing f only one). This new function is then applied to y. Because of the left-associativity of the lambda calculus, this is read as (f(x))(y) instead of f(x(y)).

An example of a use for this form: f maps x to a function that maps y to x+y. This is a change through currying of the basic addition function; instead of writing plus(x, y), we write plus(x)(y).

Length 7:


Finally, something interesting! This function of x returns not a value, but another function! The return value is λy.x (which is effectively identical to λx.y above), so this expression takes an argument x and returns the constant-value function that returns the given x.

This function has some interesting behavior in conjunction with certain others, very similar to that of the Boolean true.

Length 7:


Just like the previous example, but it returns the identity function rather than a constant-value one. As you will see soon, this can be made to behave like Boolean false.

This and the previous example are known as the Church booleans.

Length 7:


This very closely resembles the Church false; in fact, it is identical, despite the f and x in place of x and y! Through a process called α-conversion, the lambda term λx.R can become the equivalent expression λy.R', where R' is R with all instances of x replaced with y. This is intuitive enough—if f(x)=2x and g(y)=2y, then f and g are equivalent.

The different notation for this function and the Church false is to aid intuition. While the latter takes any two arguments and returns the second, this one is intended to take a function of a value (f) and a value (x). It then applies f to x zero times and returns the result.

With certain other convenient functions, this one can be treated as the number zero. This is an example of a Church numeral.

Length 8:

(λx.x) y

Application of a function again, but this one actually does something, instead of merely serving as a template! The function λx.x is applied to the variable y, done by substituting y for x (the parameter) in the return value, x. This yields y, as one might expect from applying the identity function to y.

This process of replacing each instance of the parameter in the return value with the argument is called β-reduction.

Length 9:

λf.λx.f x

Ooh, something exciting! This looks like the Church numeral for zero, but with f x in place of x. Here, the function f is applied once to x, and this result is returned. We'll call this the Church numeral for one. Noticing a pattern? Yep, the Church numeral for n returns a function of x that returns f applied to x n times.

Length 14:

λa.λb.λf.f a b

This function pairs two values, a and b, creating a function that takes a function parameter f and returns f applied to a, applied to b. These pairs, known as Church pairs, will become very useful later on.

Of course, pairs would be useless without a way of retrieving their elements:

Length 12:

λp.p λx.λy.x

This takes as input a Church pair and returns the first of the pair. Suppose p is the pair (a, b). By the definition of pairs, p applied to λx.λy.x (Church true) is equivalent to λx.λy.x applied to a, applied to b. This returns a.

Length 12:

λp.p λx.λy.y

Likewise, this function returns the second element of a pair. Confirmation of this is left as an exercise for the reader (hint: it's the same as that for the previous snippet).

Length 18:

λn.λf.λx.f (n f x)

Y'know what? Rather than adding a separate snippet for each natural number, why don't we include a recursive way of defining them? This is the successor function, one which takes as input a Church numeral and returns the next.

Here's an example: let's call this function on 1's Church numeral, λf.λx.f x. This gives us (λn.λf.λx.f (n f x)) (λf.λx.f x), which is by α-conversion equivalent to (λn.λf.λx.f (n f x)) (λg.λy.g y) (this is done to avoid name collisions). β-reduction turns this into λf.λx.f ((λg.λy.g y) f x).

Apply β-reduction once more, inside the parentheses, and we have λf.λx.f ((λy.f y) x). Again! λf.λx.f (f x)... Ooh! This looks like what I would expect two's Church numeral to be! How nice.

Another look at the successor function reveals that it is quite intuitive: it takes a Church numeral n and returns another Church numeral, one that returns a function f applied to n applications of f to x—that is, n+1 applications of f to x.

Length 30

λa.λb.a (λn.λf.λx.f (n f x)) b

Spamming successor functions gets tedious. Let's skip all that and define addition! This snippet takes two Church numerals a and b and returns their sum, as a Church numeral.

Of course, we must test this. Note that the outer parentheses contain the successor function exactly; since we already understand that one, let's just call it SUCC now. Our expression becomes λa.λb.a SUCC b.

Let's add two and three (defining TWO as λf.λx.f (f x) and THREE as SUCC TWO). (λa.λb.a SUCC b) TWO THREE is β-reduced to (λb.TWO SUCC b) THREE and again to TWO SUCC THREE. This does PRECISELY what we'd hoped—it applies succession to three two times, yielding two plus three!

  • \$\begingroup\$ By the way, Vote count no-longer restricts how many snippets you can write. \$\endgroup\$
    – ATaco
    Oct 17 '17 at 22:24
  • \$\begingroup\$ Ah, I missed that. \$\endgroup\$
    – ATaco
    Oct 17 '17 at 22:25


Factoid: T-SQL is in fact Turing-Complete and can be proven (given enough upvotes).

  • 4
    \$\begingroup\$ how many upvote do you need? XD \$\endgroup\$
    – Kokizzu
    Jan 23 '15 at 2:49
  • \$\begingroup\$ Here is my upvote. Now prove it! Just kidding, but you still have my upvote. \$\endgroup\$ Jan 23 '15 at 15:38
  • 3
    \$\begingroup\$ at 8 characters I think you can actually run a command? SELECT 1 \$\endgroup\$
    – KutuluMike
    Jan 29 '15 at 23:23
  • 4
    \$\begingroup\$ Since the snippets don't have to be complete programs, just snippets, there are a number of things that could be done. ; is the standard terminator, although it is optional for most statements in T-SQL. -- indicates the beginning of a single line comment. SET can be used to assign values to variables and alter database and system parameters. /**/ defines a comment block. BREAK exits a loop. sp_who is a system procedure that provide information on users and processes. Please put something up for our upvotes. \$\endgroup\$
    – MickyT
    Feb 5 '15 at 20:46


Well, this is not my favourite language, but this definitely hasn't been covered here, and it looks like a great golfing lang to me! To those blissed to not know what it is: Mathcad is sort of like a simplified Matlab, but clunkier. It has existed since 1986, and it is one of the oldest software products of its kind.

Factoid: Mathcad is a purely-procedural programming language with type inference and a really, really weird editor: each operator is added to the program by a keyboard key or combination of keys, but gets displayed on-screen as a (sometimes quite long) keyword.

Oh, and it doesn't support spaces, except in strings. And no tabs or linebreaks. Even if you have a very long line of code. Yes, Mathcad is weird.

Length 1

Here's a simple program in Mathcad:


This is a perfectly valid program. It declares a (global) variable a. Mathcad doesn't have any constants. And, since it uses type inference, this variable can become anything Mathcad can make it, from an integer to a matrix. Cool, huh?

Interesting fact: I call it a "variable", but, theoretically, Mathcad does not have any global variables, only redefinable global constants that can be redefined to have a new value, albeit only in global scope.

Another interesting fact: that thing is also a function. I'll explain it later. Just believe me for now.

And yes, this declaration is completely, totally useless. You can even say this causes problems as it limits the key shortcuts we can use if we decide to define it in another statement.

Length 2

Here's another simple valid program in Mathcad:

a' (equivalent to 'a)

Formatted as (a)

What does this do? This takes our newly declared a into parentheses! This doesn't do anything really, but is still valid code, too. Parentheses in Mathcad are normally used in arithmetical expressions.

I hope you're beginning to see the sheer weirdness of Mathcad. An apostrophe as a shortcut for parentheses? Who could have ever guessed it? By the way, we will get the same thing if we just type in (a). But be warned, if you haven't typed in an opening parentheses before a first, no closing one allowed! Why? No idea...

Length 3

Time for some real stuff! We can do (global) variable assignment now! a:1 (equivalent to a=1 in this case) Formatted as a:=1

We've assigned the value 1 to our "global variable", making its type a (signed, no unsigned types in Mathcad) integer. Or, speaking with Mathcad's terms, we "defined the global constant a". As a wasn't defined before, = maps to global variable assignment as well as : (this won't work if a has been already defined or simply declared). Funny thing: the type is limited to the range of... [-999999999999999, 999999999999999]. Although Mathcad "boasts" calculations on numbers with as long as 17 decimal places, in reality, it will work without error with 15-decimal-place integers maximum even with peak settings (at least on my copy of Mathcad 15). Why does it even count them by decimal places? I can only guess...

Length 4

Now, some functions!

b(c) (finally something formatted just as typed)

This is a valid piece of code that is actually a function declaration, something like a C function prototype. It declares a function b with one parameter, c. Note that you can't leave the parameter list between the parentheses empty.

Why? Well, the proper Mathcad syntaxis for a 'void'-parameter function is actually... to omit the parentheses. Yep, exactly the same as declaring a "global variable". In Mathcad, every "global variable" is sort of like a parameterless function that always returns one thing - the value it was initialized to by a definition or a redefinition. I'll demonstrate it later.

Oh yes, and functions can be redefined, just like variables. However, Mathcad has no overloading, so the function called will always be the last one declared. How very, very handy.

Funny thing about our little function declaration: it is just as useless as a "global variable" declaration. It won't allow us to call itself, it won't allow us to use it to call a function with the same signature that will be added later. It will just sit there and be 100% syntactically correct.

Length 5

Let's do something fun with our functions!

c:b{1 (formatted as c := b ← 1)

Note that this definition raises a warning about redefining a built-in Mathcad unit. Yes, Mathcad is one of those languages that sport a standart library built in right into the language, just like PHP. c is internally defined as a "meters-per-second-speed-floating-point" type variable approximating the speed of light.

So what does our definition do? Nothing important, actually. It is a parameterless function that does one thing: define a local variable b, initialize it to 1, and return the result of the expression, which is also 1.

Actually, Mathcad has an explicit return operator, but it not always needed: Mathcad will return the last thing it sees in the function if it doesn't see the return. Period. Be it a value, a variable, or the result of an expression, it will be returned.

Another funny note: local function variables can have default values if a "constant" of the same name has been declared in the global scope. You can change the local variable's value, but you cannot change its global scope counterpart's value. So yeah, in that sense, Mathcad's "global variables" could be called "constants" (although I think that "weird crap" describes them much better than either of these). So, no shared function state. That's sad since Mathcad gives us no multithreading capabilities to compensate for that.

Length 6

Still not enough space for making a multi-expression function, so let's play with some ranges instead! Also, it's a good time to finally reach (numeric) evaluation.

0,2;9= (formatted as 0,2 .. 9 =)

This is a standalone expression that defines a range from 0 to 9 inclusively with a 2 - 0 = 2 step.

The operator basically works like this: range-start {optional: , range-start + range-step} ; range-end

It is then evaluated numerically by the = operator. In Mathcad, "evaluate" = "output". In this case, it outputs a (vertical) table of all the elements of this range, which are, in this case: 0 2 4 6 8. If you remove ,2, the step will default to 1, giving you 0 1 2 3 4 5 6 7 8 9.

Length 7

Ah, finally, "linebreaks" in functions!


Formatted as:

This is a function that takes no parameters and returns... 2. This demonstrates two things: Mathcad's idiotic "line breaks" and its weird and almost completely useless "sequence-point subblock" construct.

Yes, my friends, this is what Mathcad gives us instead of line breaks. ] means "add line after last value, symbol, block in parentheses or empty line". So, if you want to write an expression on one line and another expression on the next line, you have to first prepare a line for the second expression, and then write the first expression. Otherwise, the last part of your expression ends up in its own small "sequence-point" sub-block. This can be a terrible pain in the ass.

Why do I call it a "sequence-point subblock"? Because it is basically the same as the old C parentheses-and-commas sequence-point construct: (expr1, expr2, ..., exprn). To those of you who do not know what this is: it evaluates all the comma-separated expressions in order and returns the last one. The subblock above does exactly the same: it evaluates the expressions on each line in order and gives out the result of the last one. Yes, this could theoretically be useful in structuring a function. Probably.

By the way, the "sequence-point subblock" can also be used in global context. Just type in a value/symbol/block in parentheses and hit ], then the next one, etc., and when you're done, hit = to get the last value. This can be useful in... um... oh, I give up, it's also totally useless.

Length 8

And here's how you get an expression per line in Mathcad:

a:]b↑b{1 (from here on, I'll use the arrow symbols in place of the arrow keys).

Formatted as:

This is a parameterless function that assigns 1 to b and then returns it.

I think this needs a little explanation. First, we create our function with a:. Then, we add a new line to it with ]. The cursor automatically travels to the added line, so we type b there, then use the up-arrow key to return to the previous line, and there initialize b to one.

Of course, this is golfed. In Mathcad, it is easier to add as much lines in advance as you might need, then move your cursor to the first one with the mouse and start typing your expressions, hitting the right-arrow key every time you need to go to the next line. *insert facepalm here*

  • 4
    \$\begingroup\$ Mathcad prepared against hidden whitespace programs. \$\endgroup\$
    – randomra
    Jan 25 '15 at 19:59
  • \$\begingroup\$ Whilst I'm please that you have drawn attention to Mathcad, might I suggest that you become more familiar with Mathcad and edit your remarks accordingly? Mathcad is much more capable, and easier to edit, than you suggest. It does numeric computation using the IEEE 80-bit format (hence the 17 digits) but stores using the 64-bit format. It also has an arbitrary numeric precision symbolic processor. Look up Global Variables - they have a specific meaning in Mathcad. For general use, Mathcad is my go-to maths application as it's a lot simpler to get stuff up and running (I also use Matlab). \$\endgroup\$ Mar 10 '16 at 11:54
1 2
4 5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.