550
\$\begingroup\$

Notes

  • 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>

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Why preserve a tag for one question, is it still bad for SE to have untagged question? \$\endgroup\$
    – l4m2
    Commented Jan 4, 2023 at 1:43

243 Answers 243

1 2
3
4 5
9
23
\$\begingroup\$

Dart

Length 17:

a.forEach(print);

Dart's first class functions offer concise coding patterns. Here, the print function is called for each element of a. This is the equivalent of the following:

a.forEach((e) => print(e));

Length 16:

a({b: 42}) => b;

Functions can have named parameters by using curly braces. Named parameters are optionally passed in by name by the caller, and can have a default value.

print(a());      // 42
print(a(b: 11)); // 11

Length 15:

int get x => 9;

You can define getters for a class that return a value. By default defined class fields create implicit getters and setters, but you can use the get and set keywords to define explicit custom getters and setters.

Length 14:

'''a$b

 c
''';

Multi-line Strings are created in Dart using triple quotes. String interpolation still works.

Length 13:

typedef C(a);   

You can use the typedef keyword to assign a name to a function type. Here, C defines a function that takes a single argument. Now we can refer to C where we a need a function with that signature:

k(C c) => c;

And calling k:

k((a) => 4);

This is all very similar to the previous snippet, but can simplify things greatly if we need to continuously refer to a function type.

Length 12:

a(b()) => b;

Dart functions are first class. Here a is a function that takes another function as an argument and returns it. You could call a like this:

a(() => 4);

Note that the result of this is not 4, but rather a function with the signature () => dynamic.

Length 11:

int _a = 5;

Dart uses _ as a privacy modifier. Fields and methods prepended with _ can only be accessed in the library that they are part of.

Length 10:

A(this.x);

Dart has syntax sugar in place for constructors that simply set fields. When using this.field in a constructor, the field is automatically set to the passed in argument. The above concise code is equivalent to the following:

A(x) {
  this.x = x;
}

Length 9:

Z.blank()

Dart methods, including constructors, cannot be overloaded. If you want to have multiple constructors for a class, you can use named constructors instead. Using a named constructor is straightforward:

Z z = new Z.blank();

Length 8:

main(){}

The shortest Dart program you can write. Every Dart program requires a main function as an entry point.

Length 7:

a()=>4;

You can use fat arrows for short hand functions. The above code is equivalent to:

a() {
  return 4;
}

Length 6:

a as B

The as keyword allows you to cast an object to any type, in this case the variable a is cast to type B. This is very useful when you know the type of an object returned by a dynamic method and want the tooling to reflect that. For instance, if you were working with HTML and queried the DOM for an element, you could specify the type of the element, even though that type is not actually returned:

InputElement input = querySelector('#someInput') as InputElement;
// Go ahead and use input safely as an InputElement

Length 5:

'A$k'

$ is used within Strings for interpolation. In this example if k was a variable with a value of wkward, the full value of the interpolated String would be Awkward.

Length 4:

true

Unlike other languages such as JavaScript, in Dart true is the only value that is true. The same applies to false. Values such as 0, 1, '', null are not truthy.

Length 3:

var

Var allows a variable to refer to any type of object. Tools will attempt to infer the actual type of the object.

Length 2:

{}

Dart supports map literals.

Length 1:

;

Semi-colons are mandatory to terminate a statement.

Factoid: Dart is an optionally typed language, which means you can add types to aid developers and tools, but they have no effect on your program's semantics - it will run the same whether you add types, or don't, or even add incorrect types.

\$\endgroup\$
2
  • \$\begingroup\$ Can ;, {}, and var run as standalone statements without warnings or errors in Dart? I'm unfamiliar with the language. \$\endgroup\$
    – Alex A.
    Commented Jan 20, 2015 at 16:42
  • \$\begingroup\$ They can't. It will take a quite a bit of characters to get to something that will run, since Dart requires at a minimum: main(){}. \$\endgroup\$ Commented Jan 20, 2015 at 16:44
23
\$\begingroup\$

아희(Aheui)

아희(Aheui) is the first esoteric programming language which uses Hangul, the Korean alphabet. The word '아희' means '아이' in Old Korean, which means 'child'.

Aheui works similar to Befunge. It has 26 stacks and one queue.


Factoid

There is a Twitter bot which runs Aheui code for you.

You can try programs below at here.


Length 1

This is most simple program in Aheui. It does nothing and terminates.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
ㅎ
    ㅎ                  Terminates program

Length 2

아희

Yes, the name itself is also a valid, harmless program.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
아
    ㅇ                       Initial ㅇ does nothing
             ㅏ                Move cursor by one character right
----------------------------------------
희
    ㅎ                       Terminates program
             ㅢ                (not executed)

Length 3

밯망희

This is simple character code converter. Surprisingly, it is shorter than same C or Python program.

Side note: '밯망희' is pronounced similar to the word '방망이', which means 'bat'.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
밯
    ㅂ                       Push to current stack (defaults to (none) stack)
                      ㅎ       from input as character (it will be saved as integer)
             ㅏ              Move cursor by one character right
----------------------------------------
망
    ㅁ                       Pop from current stack
                      ㅇ       to output as integer (it will be saved as integer)
             ㅏ              Move cursor by one character right
----------------------------------------
희
    ㅎ                       Terminates program
             ㅢ                (not executed)

Length 4

박빠나망

One sad point about Aheui is there is no shorter expression for the integer 1. So we need two numbers and calculate with them. Since this program has no termination command, it will print 1 infinitely.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
박
    ㅂ                       Push to current stack (defaults to (none) stack)
                      ㄱ       the integer 2
             ㅏ              Move cursor by one character right
----------------------------------------
빠
    ㅃ                       Duplicate top number of current stack
             ㅏ              Move cursor by one character right
----------------------------------------
나
    ㄴ                       Pop two numbers from current stack
                               divide second number to first number
                               push result to current stack
             ㅏ              Move cursor by one character right
----------------------------------------
망
    ㅁ                       Pop from current stack
                      ㅇ       to output as integer
             ㅏ              Move cursor by one character right
                               (If cursor reaches the end of code space, it wraps)
                               (So in this case, cursor will go to 박 again)

Length 5

바뱍멍다뼈

It simply prints even numbers infinitely. It also shows how to loop Aheui programs without wrapping.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
바
    ㅂ                       Push to current stack (defaults to (none) stack)
                               if there is no final consonant, it pushes integer 0
             ㅏ              Move cursor by one character right
----------------------------------------
뱍
    ㅂ                       Push to current stack (defaults to (none) stack)
                      ㄱ       the integer 2
             ㅑ              Move cursor by two characters right
                               (In this case, cursor will go to 다)
----------------------------------------
멍
    ㅁ                       Pop from current stack
                      ㅇ       to output as integer
             ㅓ              Move cursor by one character left
----------------------------------------
다
    ㄷ                       Pop two numbers from current stack
                               add two numbers
                               push result to current stack
             ㅏ              Move cursor by one character right
----------------------------------------
뼈
    ㅃ                       Duplicate top number of current stack
             ㅕ              Move cursor by twoe character left
                               (In this case, cursor will go to 멍)

If we make this program into infinite one way program, it will be:

바박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망...
\$\endgroup\$
23
\$\begingroup\$

Lisp

Factoid

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)

(main)

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)

(ex)

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?)

\$\endgroup\$
4
  • 1
    \$\begingroup\$ "Unique" is one word for Lisp's parentheses. I'd probably go with "excessive." :) \$\endgroup\$
    – Alex A.
    Commented Feb 21, 2015 at 4:14
  • 2
    \$\begingroup\$ @Alex Say what you wish. I stand by Lisp. \$\endgroup\$
    – robbie
    Commented Feb 21, 2015 at 14:42
  • \$\begingroup\$ Don't get me wrong, I think Lisp is great. Just lots and lots of parentheses. \$\endgroup\$
    – Alex A.
    Commented Feb 21, 2015 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
    Commented Feb 22, 2015 at 2:06
23
\$\begingroup\$

Labyrinth

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.

Factoid

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

Grid:
'
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...

90.

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

90.090.090.090.090...

and so on, repeatedly printing Z.

Length 4 snippet

4!\@

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

<.$,23>

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:

.$,23><

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:

<.$,23>

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

_v"
 "
 )"

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:

_)"
 v
 ""

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).

\$\endgroup\$
3
  • 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\$ Commented Sep 5, 2015 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\$ Commented Sep 22, 2015 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\$ Commented Nov 7, 2016 at 15:51
23
\$\begingroup\$

Plurp

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

1i

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

3 characters

)s;

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

4 characters

1~i;

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

5 characters

'a's;

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

123|i;

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

8[42i];

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

42&"i"i;

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

39&'|||s;

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!

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

MarioLANG

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

\$\endgroup\$
2
  • \$\begingroup\$ Update already! This sounds pretty cool. :) \$\endgroup\$
    – Nebula
    Commented Oct 13, 2015 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\$ Commented Oct 26, 2015 at 21:30
23
\$\begingroup\$

MATL

Factoid

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!)

s

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:

Xs

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

3$:

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!)

:t!*

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

`@EDT

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

tZp2#)

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

t4Y2m&)

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

"@YfdA?@

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

7L&!*Xs6Be!

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

:i:!+t0)/3YG

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.

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

Kotlin

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 {
  // ...
}

Then

lock(l) {foo()}

Would be compiled into

lock.lock()
try {
  foo()
}
finally {
  lock.unlock()
}

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
println(x.substring(3))

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 ->
}
\$\endgroup\$
0
22
\$\begingroup\$

AppleScript (or osascript, from command line)

Factoid

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

1

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.

1

Length 2 Snippet

it

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

me

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

«script»

Which is how AppleScript defines itself.

it

Length 3 Snippet

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

{1}

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).

array

Length 4 Snippet

tell

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

log""

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.

log

Length 6 Snippet

repeat

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

try
end

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

activate

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).

finder

Length 9 Snippet

keystroke

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

keystroke

Length 10 Snippet

set x to 1

Finally.

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
end

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.

clipboard

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 ""

clipboard2

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.

string

'A string is pretty much "TEXT"'

cappa

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

doubt

'I'm kinda doubtful of reality.'

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

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

Desmos

(View them here!)

17-vote

\frac{d}{dx}x^4+x

Derivatives!

16-vote

\prod _{n=1}^x n

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

15-vote

\left[xx\right]

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

14-vote

\frac{-3}{x^2}

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

13-vote

-x^2/\cos x^2

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

12-vote

x^x+y^y=xxy

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.

11-vote

ex^2-x=\pi 

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

10-vote

r=.5\theta 

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

9-vote

3x\ge 4y^2

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

8-vote

\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.

7-vote

\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.)

6-vote

\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.

5-vote

x=y^2

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

4-vote

2x^3

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.)

3-vote

a=5

Desmos supports the definition of variables.

2-vote

.3

Desmos supports decimal numbers without the leading zero.

1-vote (thanks!)

7

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

0-vote

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

\$\endgroup\$
3
  • 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
    Commented Sep 29, 2015 at 2:03
  • \$\begingroup\$ @ThomasKwa Thanks ^_^ I will. \$\endgroup\$ Commented Sep 29, 2015 at 2:13
  • 1
    \$\begingroup\$ Link for the interested \$\endgroup\$
    – DanTheMan
    Commented Sep 29, 2015 at 3:07
21
\$\begingroup\$

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).

Notes:

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:

1:

D;

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.

2:

L:

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:

asm

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:

Date

or

Time

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:

Free;

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:

Swap(8)

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:

Repaint;

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:

1:

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).

2:

{Comment}

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:

SendToBack;

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.

\$\endgroup\$
21
\$\begingroup\$

CSS

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

input:checked

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

display:flex

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

:last-child

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

<section>
  <p>Foo</p>
  <p>Bar</p>
  <p>Baz</p>
</section>

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

!important

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

max-width

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

q::after

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

b{top:0

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

:hover

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

[alt]

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

#38b

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:

#38b
(source)

Length 3 snippet

p#s

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

.a

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.

Factoid

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.

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

Inform 7

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

Factoid

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

X:Y

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

X YY

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

"[s]"

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.

\$\endgroup\$
20
\$\begingroup\$

Hexagony

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)

9!@

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)

H;i;@

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)

40;);(

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
print(c)
end

Length 8 snippet (try it here)

/+!=/1}~

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:

11213214421574217184218758422047684222352684224400368422...

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:

1
12
132
1442
15742
171842
1875842
20476842
223526842
2440036842

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.

\$\endgroup\$
6
  • \$\begingroup\$ I'm upvoting this, even if it means beating my answer. Hexagony is so fun! \$\endgroup\$
    – user46167
    Commented Dec 17, 2015 at 20:27
  • \$\begingroup\$ Fibonacci can be done in 6 with no separator, and 18 with, afaik. \$\endgroup\$ Commented Dec 18, 2015 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\$ Commented Dec 18, 2015 at 20:04
  • 1
    \$\begingroup\$ +1 for "I still don't get it" \$\endgroup\$
    – user45941
    Commented Jan 15, 2016 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\$ Commented Apr 5, 2016 at 3:03
20
\$\begingroup\$

Charcoal

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
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

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*
**c**
**b**
cbabc
**b**
**c**

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

7 bytes

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

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

6 bytes

Charcoal> aJ³¦³a
a    


    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
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa

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: 

asdf

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

While(InputString()) {
    Print(i)
}

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
a

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

Factoid:

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.

\$\endgroup\$
19
\$\begingroup\$

Z80 Machine Code

Factoid

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.

\$\endgroup\$
3
  • \$\begingroup\$ I just started page 4 of this question! \$\endgroup\$
    – CJ Dennis
    Commented May 18, 2015 at 6:39
  • \$\begingroup\$ if it is compatible to the 8080, how is the Z80 machine code different from 8080 machine code? \$\endgroup\$ Commented Sep 7, 2015 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
    Commented Sep 14, 2015 at 13:33
19
\$\begingroup\$

beeswax

Factoid:

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:

21
3β0
 45

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

p{N<P{*
>~+d

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.

Explanation:

          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
p
>~        [0 1 1]•
  +d      [0 1 2]•
   <
  N                   \n
 {                     2
p
>~+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:

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

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.

_8F+++P]f1Fw

Explanation

                  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)

_3F..}`[2J`

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

• marks top of stack
             lstack
_            [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)

_Z~8~]f1Fw

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]•                                 
         w

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)

_4F(@0@D

Explanation:

          lstack
_         [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

Result:

 _4F(@0@D


@

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)

_T";@Z}

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

Examples:

julia> beeswax("snippet7.bswx")
i0

Program finished!

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

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

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

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

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

Length 6 snippet (Introducing lstack I/O)

*T~T+{

Introducing new instructions: T and ~

Explanation: ( marks top of stack)

        lstack

*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")
i3
i5
8
Program finished!

Length 5 snippet

_9FB{

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)

>_{j

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.
\$\endgroup\$
1
19
\$\begingroup\$

Seriously/Actually

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

[1,2,3,4,5];♀ⁿσ

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

1WX╚;;S=YWX♂.X

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!):
`.`M

Length 13 snippet

:12345678;;+▼

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

[[1,2],[3,4]

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.

↑↑↓↓←→←→ba

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

,▓r`P`M

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.

Output:

1.61803398875
(-1+1.22464679915e-16j)

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

:1+2j

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

asdf

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

1W

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

H

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

Factoid

Seriously got its name from this challenge.

\$\endgroup\$
6
  • \$\begingroup\$ Is the secret easter egg code: Seriously?? Just a random guess. \$\endgroup\$ Commented Nov 20, 2015 at 10:29
  • \$\begingroup\$ @DJgamer98 Try it and find out :) \$\endgroup\$
    – user45941
    Commented Nov 20, 2015 at 22:44
  • \$\begingroup\$ -1 interpreter doesnt exist \$\endgroup\$ Commented Apr 7, 2016 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
    Commented Apr 7, 2016 at 2:38
  • \$\begingroup\$ @CatsAreFluffy What do you mean an interpreter doesn't exist? seriously.tryitonline.net \$\endgroup\$
    – mbomb007
    Commented Apr 20, 2016 at 16:00
19
\$\begingroup\$

TeX

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.

\$\endgroup\$
1
  • \$\begingroup\$ You have 6 more facts to add... :) \$\endgroup\$
    – Alan Munn
    Commented Jun 24, 2016 at 23:15
18
\$\begingroup\$

Perl

Factoid
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;
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
&a;
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
1+1;
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
$_=3;
This assigns a scalar variable in Perl. See that $? That's what makes it a scalar. This assigns $_ with the value 3.
Length 6
print;
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
s/b/B/g
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
@l=(3,4)
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
if(2>1){}
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.)

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

Fishing

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

Factoid

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

v+

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

>+CI

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

v+CC
  IN

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

Dock Length 3

v+CCC
  `A`

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

>+_
  C`
  C3
  C`
  Cn

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

v+CCCCC
  `ab`r

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
v+C^CDCC
  `

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

v+CCCCCCC
  `4`{`1`

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

v+CCCCCCCC
  `185`nSN

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

v+CCCCCCCCC
  `2015`l{N

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

v+CCC+CCC+CC
`p`ersonally
unliquidated
disjunction`
liver`morium

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.

v+CCC+CCC+CC
..`er.......
......ida...
..........n`

Dock Length 12

v+CCCCCCCCCCCC
  `9`n{`8`n}aP

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

v+CCCCCCCCCCCCCCCC
  `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!

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

PARI/GP

This 'language' is the combination of an interpreted language, GP, a C library called PARI, and a REPL called gp. It is a domain-specific language, specializing in algebraic number theory. You can do math very easily in GP, but some things (like string manipulation) are impractical.

Length 1: '

This command can be used to quote, but not in the usual way. 'x means "the literal polynomial x, not the value in the variable x". In postfix, it means the derivative. Tricky example: 'x' is 1 -- the derivative of the polynomial x. (But it is the 0th-degree polynomial 1, not the integer 1: 'x'==1 is true, but 'x'===1 is false since type('x') is "t_POL" not "t_INT".) ' can also be used on functions, where it means the numerical derivative: sin'(x) is the same as cos(x), up to roundoff error at least.

Length 2: <-

This command is used in set-builder notation. If you want to take a vector v and select only those values which satisfy f(x), you can run [x | x <- v, f(x)]. You can also use [g(x) | x <- v, f(x)] to apply the function g to all such terms.

Length 3: Mod

Most languages have a modulus operator, but GP also has the command Mod, which converts a number into an integer-mod-m object. You can then do exponentiation, division, and other operations naturally, and they are fast. So (99^8388607)%8388607 is slow (2 seconds) while Mod(99, 8388607)^8388607 is fast (less than a microsecond). You can also use this to do modular inversion using the extended Euclidean algorithm: 1/Mod(3,7) gives Mod(5,7) because (3*5)%7 = 1. (See also gcdext.)

Length 4: fold

This command allows a vector to be combined pairwise with a given function. Note that some functions already fold automatically where that would be useful: lcm, gcd, Str, and (in some sense) chinese.

Length 5: 3^3^3

This yields 7625597484987, demonstrating not only that ^ represents exponentiation rather than a bitwise operator but that exponentiation is right-associative. This is the mathematical convention, but many other languages are left-associative instead, giving the much smaller 19683. See PARI/GP Operator Precedence or section 2.4 in the User's Guide to PARI/GP.

Length 6: fordiv

GP has many types of loops built in which go beyond the standard C-style for, do, and while. This one takes a number and loops once for each of its divisors, setting the dummy variable equal to the divisor itself. There is also the summation version sumdiv which adds up all the results of the inner loop. Thus sumdiv(720720, n, n^2) gives the sum of the squares of the divisors of 720720. (You could already do this with sigma(720720, 2) but this version is more customizable.) Note also that fast factorization techniques are used, not just trial division, so the result is computed quickly.

Length 7: V ec(x)

This demonstrates two principles of GP. First is the ability to convert between different forms with conversion commands like Pol (polynomial), Vec (vector), Vecsmall (vector of small integers), Set (set), Mat (matrix), etc. Second is the fact that the parser completely ignores spaces, so V ec is the same as Vec. Space is added only for readability. This can, however, have interesting effects on constrained coding!

Length 8: eta(I/4)

PARI/GP includes a large number of built-in special functions. eta(z) represents an infinite product (the Dedekind eta function) and is computed efficiently, but you can also compute this instance 'directly' as prodinf(n=1,1-exp(-Pi*n/2)).

Length 9: asinh('x)

As hinted at by the first snippet, ' means that x is to be treated as a formal variable. (By default it, and all other variables, are purely formal, but you could also assign to it: x=1, for example. If you haven't assigned to it you can drop the '.) When the inverse hyperbolic sine function gets an argument which includes a formal variable, it computes a Maclaurin series in that variable, so this results in x - 1/6*x^3 + ... where the terms continue depending on your settings (default(seriesprecision) controls these settings). You can also force GP to use a desired number of terms with the O command: asinh(x+O(x^4)).

Length 10: -eint1(-9)

eint1 is the exponential integral, which can be used (among other things!) to estimate the number of primes up to a certain number. This provides an estimate for the number of primes up to e9, and it's pretty good: the exact answer is 1019 and this gives about 1037.

Length 11: teichmuller

teichmuller(x) gives the Teichmüller character of x, that is, the unique (p-1)-th root of unity congruent to x / p^k modulo p with k maximal. PARI/GP has strong support for class field theory and has many nontrivial functions built in.

Length 12: hilbert(3,5)

Computes the Hilbert symbol of 3 and 5. Since the third argument is not given, the command defaults to doing the calculation 'at infinity', that is, the completion is the real numbers. You could also pass a prime p in which case it would instead use the p-adic numbers as the completion.

Length 13: thue(x^2+3,7)

This is where GP's specialized functions begin to shine. thue solves a Thue equation, which is an irreducible bivariate homogeneous polynomial of degree at least 3. This example uses x2 + 3 y2 = 7, which has four integer solutions. This command has many additional options, for which see the help entries ??thue and ??thueinit. Note that although the polynomial of interest is bivariate and homogeneous, it is entered in GP as an inhomogeneous univariate polynomial. This can be achieved by setting either variable to 1.

Length 14: Vec(eta('x)^2)

This computes the Taylor series of the Dedekind eta function, squares it, and returns the coefficients. This is a slick way to compute sequence A002107 in the OEIS, the number of partitions of a number into an even number of distinct parts minus number of partitions of the same number into an odd number of distinct parts, with 2 types of each part. (Replacing the 2 in the program with a different number changes the number of parts accordingly; using 1, for instance, yields A010815 instead.)

Note that the ' is optional (but good form), see the length 1 snippet.

Length 15: hyperu(-38,9,1)

This computes 76! * (binomial(38,0)/38! - binomial(38,1)/39! + binomial(38,2)/40! - ... + binomial(38,38)/76!) using the U-confluent hypergeometric function. See A006902 in the OEIS.

Length 17: lcm(znstar(n)[2])

This computes the Reduced totient function psi(n).

Length 25: (Mod([1,1;1,0],m)^n)[1,2]

\$\endgroup\$
17
\$\begingroup\$

T-SQL

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

\$\endgroup\$
4
  • 4
    \$\begingroup\$ how many upvote do you need? XD \$\endgroup\$
    – Kokizzu
    Commented Jan 23, 2015 at 2:49
  • \$\begingroup\$ Here is my upvote. Now prove it! Just kidding, but you still have my upvote. \$\endgroup\$ Commented Jan 23, 2015 at 15:38
  • 3
    \$\begingroup\$ at 8 characters I think you can actually run a command? SELECT 1 \$\endgroup\$
    – KutuluMike
    Commented Jan 29, 2015 at 23:23
  • 5
    \$\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
    Commented Feb 5, 2015 at 20:46
17
\$\begingroup\$

Tcl

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

2 chars

{}

Empty string literal.

5 chars

end-1

Used as index, means the second last element.

6 chars

if 0 ?

Just a comment. Can span multiple lines.

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

Fortran

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
         RETURN
       END

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:

12HABC

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:

!$omp

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:

type

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:

end

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:

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.

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

Vitsy

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

Factoid:

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.
5

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:

"N

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.

'Nߟ

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

I\iO

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

DmN
0

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:

'rd3*Z
'      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

DpD(!<N

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

R\&Yv?vN

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:

00k
;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?

")(etaD"nZ

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

Forkbomb = sad

Length 14 Snippet

v&v\[y1-\?v?v]

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:

;
v&v\[y1-\?v?v]

And called like so:

01k
;u something.vt

Explanation:

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.

\$\endgroup\$
3
  • \$\begingroup\$ How come Date() is backwards in length 10? \$\endgroup\$
    – GamrCorps
    Commented Dec 9, 2015 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\$ Commented Dec 9, 2015 at 14:08
  • \$\begingroup\$ Ah, I see. Thanks. \$\endgroup\$
    – GamrCorps
    Commented Dec 9, 2015 at 14:12
17
\$\begingroup\$

GolfScript

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

Factoid

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

-1%

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

2base

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/.&n*

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

{,}$-1=

[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

":n`":n`

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

"#{size}"

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

{9(:9.(}do

This prints:

87654321

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ +1 can we have some more? \$\endgroup\$ Commented Jan 14, 2016 at 5:55
17
\$\begingroup\$

///

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

Factoid

/// 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

\n

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

/
/☃/
(newline)

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

/☃/☃8/☃

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:

☃
(☃)
☃8
(☃)8
☃88
(☃)88
☃888
...

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

/☃/8/☃/8/B

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

/☃/8//8/☃/☃

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:

/8/☃/☃
/8/(☃)/(☃)
/8/8/8

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

Length 12

/☃/\/8\//☃B/

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

☃B/
(☃)B/
/8/B/

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.

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

Pyke

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:

r

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

1: GOTO_START

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:

SB

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:

]UP

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

F\_+

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.append(i+"_")
rtn = "".join(rtn)
print(rtn)

5 bytes

#.b){

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

C695@]

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

.dॳ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

1?tY/r"Z

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

S#2%!)1|e

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

Cy1H30M"+t

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

V.X".X-+||"

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?

CB"Jupiter"@

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

~1#_P)D3M*+mP

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

y0:0"w𕆠Vs5
​

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

.dȇጾȞĶl5

Try it here!

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

\$\endgroup\$
0
17
\$\begingroup\$

HQ9+

Factoid:

HQ9+ is a joke programming language, invented by Cliff L. Biffle in 2001. It is a golfing language, that has a very small source code for the most common programming exercises, due to its small set of strategic built-ins.

Length 1

Q

HQ9+ has a very short quine. The Q built-in prints the source code of the entire program.

Length 2

9+

Speaking about crazy built-ins, HQ9+ is almost comparable to Mathematica. This program prints the entire lyrics of "99 bottles of beer on the wall", before it increments the accumulator and terminates.

Length 3

9H9

Commands can be mixed and matched in any order you want. This program, for instance, takes a break and greats the world between two passes through the already mentioned song "99 bottles of beer on the wall."

Length 4

HQ9+

Yup, The name of the language is actually a syntactically valid program by itself. One thing to notice here is how Q behaves when there are other characters in the program as well. In between hello world and 99 bottles of beer, it prints "HQ9+". While not a quine, the source code is at least part of the output.

Length 5

+++++

There are no other operations than + that can be applied to the accumulator. Thus, if we want to increase it by five, this is the shortest way to do it. While backwards compatible with HQ9+, the popular object-oriented extension of the language by David Morgan-Mar, HQ9++, is also going to create two new subclasses of the generic superclass if this code is executed. The output is the same though.

Length 6

QH99QH

We have seen that HQ9+ is capable of only a limited number of outputs, however, it can still output any information. Using the highest density of information per command (e.g. avoid to increase the accumulator), the flow rate of information is log2(3) bits per command. For many languages, this is not known exactly, but for English text it is assumed to be around 1.3 bits per character, a little less than HQ9+. I have here as an example chosen a tertiary encoding, where the output of the H command here represents a 0, Q represents 1 and 9 represents 2. Using that, the output of the program can be interpreted as "SE" for Stack Exchange.

Length 7

QQQQQQQ

Surprisingly many get this one wrong, they think Q prints just a Q. But Each Q actually prints the whole source code of the program, here resulting in

QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
(49 of them)

That is a great tool for demonstrating quadratic growth, and make it possible for HQ9+ to be used in surprising ways, like in this answer printing twice the length of the program to STDOUT.

Length 8

+++Q++++

As the + command is effectively a NOP regarding output, a single Q placed anywhere in a string of + can be used to produce a quine of arbitrary length.

Length 9

BURLESQUE

Is this a quine or not? That depends on the interpreter used. It is not very clear in the specification if invalid characters should be ignored or not. In the interpreters that do ignore such characters, this is proper quine. Others just throw an error. That is not necessarily more correct either, as error management is not accurately specified either. (Ehm.. It is not mentioned...)

Length 10

H+H+H+H+H+

Many people will probably have some concerns about to language because of the very permissive specification potentially leading to spaghetti code or bad programming practises. This example is an attempt to disprove this myth by adapting principles from structured programming, by carefully incrementing the accumulator after each successfully executed statement. Each and every instruction is thus properly clarified.

Length 12

219661 beers

Is it still possible to find interesting long programs in HQ9+? Well, we can take a look at iterating programs. If the above snippet is run through an interpreter ignoring non-existing commands, the 9 triggers our familiar song. The output, if you analyse it, contains exactly 60 9's. Suppose we feed that back as an input, we end up with 60 new runs of the song. The number grows exponentially, so after three iterations, we have reached a total of 219661. Also worth mentioning is the growth of "Hello, world!". Each run of the song spawns 101 new ones (2 per verse, one extra in "tHe store"), and each one produces one child in the next iterations. That should give us 369761 in total on the third iteration.

\$\endgroup\$
1 2
3
4 5
9

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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