496
\$\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\$

226 Answers 226

23
\$\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\$
  • \$\begingroup\$ seems like the "keystroke" snippet showcases the "current date" feature \$\endgroup\$ – Ven Apr 26 '16 at 13:34
  • 1
    \$\begingroup\$ @ven Whoops, I'll fix that. Thanks. \$\endgroup\$ – Addison Crump Apr 28 '16 at 7:05
  • 1
    \$\begingroup\$ 17 votes. Please update your answer ASAP. (don't panic though) \$\endgroup\$ – Erik the Outgolfer May 30 '16 at 6:59
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\$
  • \$\begingroup\$ Why is this so popular!? \$\endgroup\$ – BobTheAwesome Jul 1 '15 at 13:53
  • 1
    \$\begingroup\$ Are you thinking of names yet? \$\endgroup\$ – mbomb007 Sep 4 '15 at 22:03
  • \$\begingroup\$ No, I really need to add more programs though. \$\endgroup\$ – BobTheAwesome Oct 16 '15 at 2:13
  • \$\begingroup\$ le bump please add programs* \$\endgroup\$ – Conor O'Brien Jul 26 '16 at 0:48
  • \$\begingroup\$ Hi! I've finally gotten around to re-making a working interpreter. I will be adding programs soon! \$\endgroup\$ – BobTheAwesome Feb 5 '17 at 16:12
23
\$\begingroup\$

PostScript

Factoid

PostScript is a language designed for printer rasterization engines. It is nonetheless a mostly feature complete programming language based on stack manipulation. This makes it relatively easy to extend the drawing primitives.

PostScript can be executed by many devices, and programs. Aside GhostScript, if you include a encapsulation header, you can use programs such as Word, Illustrator, Indesign as preview (possibly live if you link the file) for your code. This means that surprisingly many users even on the Windows platform can execute your program with no extra installation.

One char snippet

2

Puts the number 2 topmost on your execution stack. Nothing fancy done with this yet, but hey, we have allocated some memory.

Two char snippet

==

Print and remove topmost item in stack to stdout. Since not all systems are guaranteed to have a meaningful stdout this may in fact do nothing. Raises an error if stack is empty.

Three char snippet

(a)

Push a string containing a to the stack.

Four char snippet

save

Save the state of your virtual machine and put a save object on top of your stack. You can then use restore on this object to return to the global saved state at any time.

Five char snippet

5 sin

Calculate the sine of 5 degrees. Postscript quite universally thinks of angles as degrees, as opposed to more mathematical radians of many languages use.

Six char snippet

moveto

When executing drawing instructions, PostScript acts like a plotter (or pen in hand). The moveto command moves the virtual pen to a location specified by the two topmost items on the stack; topmost being the y direction and the second the x direction.

Seven char snippet

1 2 add

And finally we have enough chars to actually compute something trivial. Here we push 1 and 2 to the stack. Calling add then pops them both, adds them together, and pushes the sum onto the stack. Leaving 3 on top of the stack.

Eight char snippet

/v 9 def

Define symbol v as 9. This is mostly equivalent to doing v = 9 in most other languages. So now the previous example could look as v 2 add and it would result in 11 in the stack.

Ten char snippet

0 2 8{}for

A for-loop. Normally you'd add spaces around the function {} but I'm running out of chars. This produces numbers even numbers 0 through 8, as the stepping is 2. So the stack after this would be 0 2 4 6 8. 20 more chars and we can start drawing stuff. (not a good language for golfing)

Eleven char snippet

/a {add}def

Simple function definition; the function goes between the curly brackets and acts upon the stack. Note how it uses same mechanism as snippet 8. Now you could write the 7 char snippet as 1 2 a.

Twelve char snippet

4 3 gt{1} if

So here you go some flow control, if 4 is greater than (gt) 3 execute function {} which in this case deposits 1 in the stack.

Thirteen char snippet

0 0 6 0 5 arc

Make a 5 degree arc with a radius of 6 at the origin (0, 0). Note this does not actually draw anything yet; it prepares for drawing by constructing something that's called a 'user path'.

Fourteen char snippet

20 0 translate

Changes the transformation matrix so that your drawings are henceforth positioned 20 units more right. This is useful if you want to repeat the same drawing routine in different places. PostScript coordinates are measured from the bottom left corner of your drawing surface and each unit is one PostScript Point (a unit Adobe invented) that is 1/72 of an inch.

Eighteen char snippet

1 1 5 5 rectstroke

Draws a stroked rectangle onto the canvas in the lower left corner of your page.

Twenty-one char snippet

4 4 moveto 2 5 lineto

Puts a line segment into the drawing buffer.

\$\endgroup\$
  • \$\begingroup\$ @mbomb007 Edit appreciated \$\endgroup\$ – joojaa Jun 24 '15 at 8:23
  • \$\begingroup\$ Need one more number for x y radius ang0 ang1 arc -. I only noticed this because I've implemented arc. \$\endgroup\$ – luser droog Jan 14 '16 at 6:03
  • \$\begingroup\$ When you get to 19, you can 0 0 1 1 rectstroke. \$\endgroup\$ – luser droog Jan 14 '16 at 6:39
  • \$\begingroup\$ @luserdroog right you are will fix as soon as i have a computer in front of me. \$\endgroup\$ – joojaa Jan 14 '16 at 9:22
23
\$\begingroup\$

QBasic

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

Factoid

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

Length 1

1

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

Length 2

?a

Lots of stuff going on here:

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

Length 3

CLS

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

 0 
 0 
 0 

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

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

Length 4

BEEP

Does just what you think it does.

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

Length 5

?2^42

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

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

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

Length 6

?1:RUN

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

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

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

Length 7

INPUT x

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

? Jabberwocky
Redo from start
? 

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

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

Length 8

PLAY"CF"

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

Length 9

SCREEN 12

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

Length 10

?4*ATN(1#)

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

Length 11

COLOR 2:?42

Time to get colorful.

Green 42 (Shown 2x actual size)

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

The 16 colors in QBasic

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

COLOR 25,4

and see this:

Blinking "Press any key"

Trippy.

Length 12

DRAW"F3U7R9"

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

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

Length 13

LOCATE 7,8:?9

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

Using LOCATE command

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

Length 14

GOTO a
?1
a:?2

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

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

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

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

than the Python equivalent:

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

Length 15

RANDOMIZE TIMER

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

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

Random-number seed (-32768 to 32767)? 

Nobody can say QBasic isn't user-friendly.

Length 16

CIRCLE(9,9),8,,2

Graphics command: combine with snippet 9 to run.

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

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

Arc of circle (Shown 2x actual size)

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

CIRCLE(51,26),50,,,,0.5

Half-squashed circle

Length 17

LINE INPUT s$:?s$

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

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

Length 18

LINE(1,1)-(9,9),,B

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

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

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

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

* Slight hyperbole.

Length 19

?0:PAINT(10,4),9,15

Graphics command: combine with snippet 9 to run.

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

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

Length 20

?ASC(INPUT$(1));
RUN

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

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

 65  66  67  49  50  51  27  13  9  8 
\$\endgroup\$
  • 1
    \$\begingroup\$ I know this is old, but I gave you the 13th upvote, and I'm interested in seeing what you can do with 13 characters (you mentioned it in your length 3 snippet). I grew up on QB45 and absolutely loved it. \$\endgroup\$ – vastlysuperiorman Mar 31 '16 at 19:28
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\$
  • \$\begingroup\$ Update already! This sounds pretty cool. :) \$\endgroup\$ – Florrie Oct 13 '15 at 12:22
  • \$\begingroup\$ @towerofnix Had to go inactive for a while, didn't realize how popular this became. I've added 5 new snippets. \$\endgroup\$ – ASCIIThenANSI Oct 26 '15 at 21:30
23
\$\begingroup\$

Scratch

Oops! I kind of feel like a terrible person for not updating this lately. I'll try to be more consistent with my updates, e.g. when somebody votes I'll update.. Forgive me? :)
Oops! Wow, did it again. A link or two was broken; that should be fixed now.


Scratch is a graphical programming language created by MIT. Because it's graphical and block-based, rather than counting the number of characters, I'm going to count the number of blocks (after all, the number of characters could change with translations).

Rather than getting a screen shot of every single script I'll give you a link to a Scratchblocks page. I'll also post the code for it below.

This answer is in development! ;)

Um, also, maybe read the scripts from bottom to top..? :P


Length 11

Code:

when [space v] key pressed
set [Playing? v] to [1]
set [Score v] to [0]
reset timer

when this sprite clicked
if <(Playing?) = [0]>
  change [Score v] by [1]
end

when [timer v] > (10)
set [Playing? v] to [0]

Well, we've got three whole scripts here! This should be simple enough to understand, but I'll explain it anyways.

when [space v] key pressed
set [Playing? v] to [1]
set [Score v] to [0]
reset timer

When the space key is pressed, we want to set the playing variable to 1 (e.g. true), the score variable to 0 (e.g. no points yet), and reset the timer. The timer is an important part of this project!

when this sprite clicked
if <(Playing?) = [0]>
  change [Score v] by [1]
end

When the sprite is clicked on, if we are currently playing, change the score by 1.

when [timer v] > (10)
set [Playing? v] to [0]

When the timer is greater than 10 (e.g. 10 seconds have elapsed since the timer has last been reset) set the playing variable to 0. Because it is now 0, in the when-sprite-clicked script the score is no longer increased.

By the way, here is the costume that the sprite uses:

Sprite Costume

A key bit of information about this project is that you can have multiple scripts inside a single project. Each of these scripts will be called according to their hat block, so when this sprite clicked will happen when this sprite is clicked on!

Getting a bit technical here, but Scratch does not use multiple threads. Instead you should think of scripts being stuck into a list of things to do. It's a bit complicated but works similarly to the way JavaScript does.

Also, keep in mind that many blocks will automatically update the screen (as well as control events, for example, a loop looping) and will tell Scratch's interpreter to go on to the next script occurring simultaneously. You can get around this by putting your script inside of a run-without-screen-refresh custom block as shown in length 8.

Length 10

Code:

when GF clicked
set tempo to (pick random(30) to (120)) bpm
set [Note v] to [55]
repeat (3)
  play drum (15 v) for (1) beats
end
repeat (10)
  play note (Note) for (0.3) beats
  change [Note v] by [1]
end

This one hopefully won't blow your mind too much. It's a simple melody with a drumroll. I don't think it needs that much describing. ;)

(Scratch Official Editor) (Scratchblocks) Length 9 Snippet:

// Sprite: Cat
when GF clicked
go to x: (-130) y: (90)
point towards [Apple v]
repeat until <touching [Apple v]>
  move (2) steps
end
broadcast [got apple v]

// Sprite: Apple
when I receive [got apple v]
hide

What's so nice about Scratch is that it's scripts are very self-explanatory. I probably don't even need to explain to you what this does for you to figure it out (especially if you run the program by going to the above link).

However, this example does introduce a few new things I haven't shown yet:

  • Sprites: These are Scratch's idea of things in the world (stage). A sprite is generally what you use when you want to add a character to your scene. Whenever you open up the editor, you already get pre-loaded a sprite - it's that scratch cat! You can use as many sprites as you want in your program as well. Learn more about Sprites and how to create them on the wiki.

  • Broadcasts: A broadcast is as it sounds (literally) - it's a message that is sent through the project to every single sprite in the program. You use the when I receive hat to make something happen when a script is broadcasted. Broadcasts are a very important part of the programming language and you can learn more about them on the wiki here.

One last cool thing about this project is that if you change the numbers in the go to x: y: block it will always work - so why not try it?

(Scratchblocks) Length 8 snippet:

when GF clicked
insta

define insta
pen down
repeat (360)
  turn cw (1) degrees
  move (1) steps
end
pen up

Boom - custom procedures! I'd just like to clarify here - this is an instant custom block, or as I and some friends like to call them, atomic procedure. All that means is the block runs in a single frame - which is quite important for turtle graphics!

Here is a screenshot of the script, and the dialog I used to make the custom block:

Atomic Functions

(Scratchblocks) Length 7 snippet:

when GF clicked
ask [Hexadecimal decoder - please type a hex number WITHOUT THE 0x PART:] and wait
say (join [] ((join [0x] (answer)) - (0)))

Oh, hey! Scratch has hexadecimal decoding support! Who would have guessed?* Simply use ((join [0x] [###]) - (0)) to decode some hexadecimal.

(Scratchblocks) Length 6 snippet:

when GF clicked
set [var v] to [0]
repeat (10)
  change [var v] by (1)
  say (var) for (0.5) secs
end

Variables in Scratch are represented by their own orange blocks - to declare one, you press the button Make a variable inside the Data category. This creates a new block, name, in the Data category. To manipulate it, use the variable blocks. All variables also have an (optional) watcher which can be customized - see the watcher's wiki article for more information!

(Scratchblocks) Length 5 snippet:

pen down
clear
repeat (180)
  move (2) steps
  turn cw (2) degrees
end

Here we demonstrate - like all good programming languages should be able to - turtle graphics! Just because Scratch is a visual programming language really gives it just that extra bit of fun when you're programming, even more so with the pen!

(Scratchblocks) Length 4 snippet:

forever
  play note ((timer) mod (50)) for (0.5) beats
end

Scratch has many built in instruments - the simplest way to play a note is via the play note for beats block. Keep in mind the default instrument is 1 (piano) and the default tempo is 60bpm. Using blocks found in the Sound Category you can do things like change the instrument, play sounds you import, and even use the built in drum set!

(Scratchblocks) Length 3 snippet:

when [space v] key pressed
point towards [mouse-pointer v]
move (10) steps

When the space key is pressed, it moves the selected sprite toward the mouse. This makes it easier to demonstrate moving towards the mouse as you don't need to move the script whenever you want to change direction (and it would still only be able to go towards the east edge of the stage).


(Scratchblocks) Length 2 snippet:

point towards [mouse-pointer v]
move (10) steps

When the script is clicked, it moves the sprite ten steps towards the mouse when clicked.

(Scratchblocks) Length 1 snippet:

move (10) steps

When the script is clicked, it moves the sprite ten steps (pixels) in the direction it's facing, which, assuming you're using a non-touched-so-far sprite, will be towards the right (90° in Scratch).


Factoid: Scratch was originally released in 2007 (it was made in very early stages in 2003 or 2002 I believe) and now has over 7 million people using it (Scratchers) and over 10 11 million projects created. It's used all around the world as well. Check out the statistics page to see more stats about Scratch, and try it out online here. It's free!

* The Advanced Topics would. :)

\$\endgroup\$
  • \$\begingroup\$ Added the second. \$\endgroup\$ – Florrie Jul 17 '15 at 9:52
  • \$\begingroup\$ Added the third. \$\endgroup\$ – Florrie Jul 21 '15 at 10:01
  • \$\begingroup\$ oops I suppose I should update this \$\endgroup\$ – Florrie Aug 25 '15 at 19:11
  • \$\begingroup\$ Added the fourth, fifth, and sixth! \$\endgroup\$ – Florrie Aug 25 '15 at 19:58
  • \$\begingroup\$ Also added to the language list on the first post. \$\endgroup\$ – Florrie Aug 25 '15 at 19:59
22
\$\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\$
  • 1
    \$\begingroup\$ "Unique" is one word for Lisp's parentheses. I'd probably go with "excessive." :) \$\endgroup\$ – Alex A. Feb 21 '15 at 4:14
  • 1
    \$\begingroup\$ @Alex Say what you wish. I stand by Lisp. \$\endgroup\$ – robbie0630 Feb 21 '15 at 14:42
  • \$\begingroup\$ Don't get me wrong, I think Lisp is great. Just lots and lots of parentheses. \$\endgroup\$ – Alex A. Feb 21 '15 at 23:13
  • 1
    \$\begingroup\$ @Alex Lots of parentheses, but it's better than having all these parentheses, square brackets, and curly brackets all over the place. \$\endgroup\$ – robbie0630 Feb 22 '15 at 2:06
22
\$\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\$
  • \$\begingroup\$ I'm upvoting this, even if it means beating my answer. Hexagony is so fun! \$\endgroup\$ – ev3commander Dec 17 '15 at 20:27
  • \$\begingroup\$ Fibonacci can be done in 6 with no separator, and 18 with, afaik. \$\endgroup\$ – FryAmTheEggman Dec 18 '15 at 18:15
  • \$\begingroup\$ I've figured out what your code is doing, each time it goes around the loop, the 1 is messing up your logic. The values being printed out are: 1, 12, 132, 1442, 15742 ... \$\endgroup\$ – FryAmTheEggman Dec 18 '15 at 20:04
  • 1
    \$\begingroup\$ +1 for "I still don't get it" \$\endgroup\$ – Mego Jan 15 '16 at 7:27
  • \$\begingroup\$ I was revisiting a bunch of these, and I realised that I never explained what was happening. Oops :P Anyway, your code does: F_n = (10 * F_n-1 + 1) + (10 * F_n-2 + 1). \$\endgroup\$ – FryAmTheEggman Apr 5 '16 at 3:03
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\$

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

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\$
  • \$\begingroup\$ Maybe show off your color! ![](http://dummyimage.com/100x100/38b/38b.png) \$\endgroup\$ – Lynn May 12 '15 at 15:45
21
\$\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 to 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 defined 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, in the same order. 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 indicated 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 be computed with the builtin 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. 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 first and second, 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. With second input 3 it displays the matrix with each entry corresponding to one pixel on the screen, using a grey colormap by default.

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

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\$
  • \$\begingroup\$ I just started page 4 of this question! \$\endgroup\$ – CJ Dennis May 18 '15 at 6:39
  • \$\begingroup\$ if it is compatible to the 8080, how is the Z80 machine code different from 8080 machine code? \$\endgroup\$ – Paŭlo Ebermann Sep 7 '15 at 22:36
  • \$\begingroup\$ @PaŭloEbermann The Z80 extends four unused op-codes. All 8080 op-codes are single byte but the Z80 has multi-byte op-codes starting with CB, DD, ED & FD. A lot of these are used to address registers that don't exist in the 8080. \$\endgroup\$ – CJ Dennis Sep 14 '15 at 13:33
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\$
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\$
  • \$\begingroup\$ Is the secret easter egg code: Seriously?? Just a random guess. \$\endgroup\$ – DJgamer98 Nov 20 '15 at 10:29
  • \$\begingroup\$ @DJgamer98 Try it and find out :) \$\endgroup\$ – Mego Nov 20 '15 at 22:44
  • \$\begingroup\$ -1 interpreter doesnt exist \$\endgroup\$ – CalculatorFeline Apr 7 '16 at 0:10
  • \$\begingroup\$ @CatsAreFluffy Oh yeah I need to add the Easter egg into the language proper since I killed off the heroku app. Watch this space for more stuff once I finish the first release of v2. \$\endgroup\$ – Mego Apr 7 '16 at 2:38
  • \$\begingroup\$ @CatsAreFluffy What do you mean an interpreter doesn't exist? seriously.tryitonline.net \$\endgroup\$ – mbomb007 Apr 20 '16 at 16:00
19
\$\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\$
  • 1
    \$\begingroup\$ Judging from the snippets so far, I don't know what you can do with less than about twenty characters, but impress me. \$\endgroup\$ – lirtosiast Sep 29 '15 at 2:03
  • \$\begingroup\$ @ThomasKwa Thanks ^_^ I will. \$\endgroup\$ – Conor O'Brien Sep 29 '15 at 2:13
  • 1
    \$\begingroup\$ Link for the interested \$\endgroup\$ – DanTheMan Sep 29 '15 at 3:07
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\$
  • \$\begingroup\$ Length 8 is incorrect. It gives you an array with one array ref in it. \$\endgroup\$ – skibrianski Sep 7 '15 at 23:55
  • \$\begingroup\$ @skibrianski Thanks for pointing that out, it's fixed now. \$\endgroup\$ – ASCIIThenANSI Sep 8 '15 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\$
  • 2
    \$\begingroup\$ Heh, of course you'd do a fish-themed language, \$\endgroup\$ – Deusovi Oct 27 '15 at 18:28
  • \$\begingroup\$ @Deusovi I'm going to be perfectly honest here - I never realized the irony of that. \$\endgroup\$ – Arcturus Oct 27 '15 at 18:31
  • \$\begingroup\$ My goal for this answer is just to get to 16 so I can post Hello, World! \$\endgroup\$ – Arcturus Feb 22 '16 at 15:50
  • \$\begingroup\$ @ANerd-I 2 more to go 'till 16... \$\endgroup\$ – Conor O'Brien Apr 8 '16 at 5:24
  • \$\begingroup\$ @ANerd-I You're 14 total votes now. \$\endgroup\$ – Erik the Outgolfer May 30 '16 at 7:00
18
\$\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\$
  • \$\begingroup\$ You have 6 more facts to add... :) \$\endgroup\$ – Alan Munn Jun 24 '16 at 23:15
17
\$\begingroup\$

T-SQL

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

\$\endgroup\$
  • 4
    \$\begingroup\$ how many upvote do you need? XD \$\endgroup\$ – Kokizzu Jan 23 '15 at 2:49
  • \$\begingroup\$ Here is my upvote. Now prove it! Just kidding, but you still have my upvote. \$\endgroup\$ – Ismael Miguel Jan 23 '15 at 15:38
  • 3
    \$\begingroup\$ at 8 characters I think you can actually run a command? SELECT 1 \$\endgroup\$ – KutuluMike Jan 29 '15 at 23:23
  • 4
    \$\begingroup\$ Since the snippets don't have to be complete programs, just snippets, there are a number of things that could be done. ; is the standard terminator, although it is optional for most statements in T-SQL. -- indicates the beginning of a single line comment. SET can be used to assign values to variables and alter database and system parameters. /**/ defines a comment block. BREAK exits a loop. sp_who is a system procedure that provide information on users and processes. Please put something up for our upvotes. \$\endgroup\$ – MickyT Feb 5 '15 at 20:46
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
    \$\begingroup\$ I think you should add the {}, end-1. \$\endgroup\$ – jimmy23013 Jan 24 '15 at 9:07
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\$
  • \$\begingroup\$ How come Date() is backwards in length 10? \$\endgroup\$ – GamrCorps Dec 9 '15 at 14:03
  • \$\begingroup\$ Vitsy is a top access only stack. When I do eval, it grabs it in reverse order of how I put it into the stack. That means that )(etaD is read as Date() by eval. @GamrCorps \$\endgroup\$ – Addison Crump Dec 9 '15 at 14:08
  • \$\begingroup\$ Ah, I see. Thanks. \$\endgroup\$ – GamrCorps Dec 9 '15 at 14:12
16
\$\begingroup\$

Mathcad

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

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

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

Length 1

Here's a simple program in Mathcad:

a

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

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

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

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

Length 2

Here's another simple valid program in Mathcad:

a' (equivalent to 'a)

Formatted as (a)

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

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

Length 3

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

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

Length 4

Now, some functions!

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

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

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

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

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

Length 5

Let's do something fun with our functions!

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

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

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

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

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

Length 6

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

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

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

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

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

Length 7

Ah, finally, "linebreaks" in functions!

a:b{1]2

Formatted as:

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

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

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

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

Length 8

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

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

Formatted as:

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

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

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

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

Elixir

Elixir is a functional, concurrent, general-purpose programming language built atop the Erlang Virtual Machine (BEAM). Elixir builds on top of Erlang to provide distributed, fault-tolerant, soft real-time, non-stop applications but also extends it to support metaprogramming with macros and polymorphism via protocols.

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

Length 8

fn-> end

This is an example on how to create a function, this function only returns nil, to call it, you must assign it to a variable, for example: x=fn->123 end, then call it using .(), such as: x.() that would return 123.

Length 7

[a: 12]

This is example of creating keyword list (list of key-value pair), this statements are equal to [{:a, 12}]. We could access the value using square bracket and the key, for example:

kl = [a: 12, b: 13]
kl[:b] # 13
kl[:c] # nil
kl[:a] = 14        # error!
kl = [a: 14] ++ kl # [a: 14, a: 12, b: 13]
kl[:a] # 14

Length 6

<<65>>

This is an example on how to create a binary, this would result a valid string "A", to concat the string or binary you can use <> operator, for example: "AB" <> <<67,68>> that would end as ABCD

Length 5

{1,2}

Tuple is just like a list, to get the length, use tuple_size function, to get the element on n-th position, use elem function, to change the value of n-th position, use put_elem function. To find more about the difference between lists and tuples, visit this link.

x = {3,"yay"}
elem(x,1)
# "yay"
put_elem(x,1,"wow")
# {3,"wow"}

Length 4

[12]

This is an example on how to create a list, to get the length, use length function, to append with another list, use ++ operator, to remove all first element that exists in another list we could use -- operator. To get the first and last element use hd and tl function. To get the n-th element, use Enum.at, to set, use List.replace_at.

[1, 2, 3] ++ [4, 5]
# [1, 2, 3, 4, 5]
list = [1, 1, 2, 2, 3, 4] -- [2,3]
# [1, 1, 2, 4]
hd(list)
# 1
tl(list)
# 4
Enum.at(list,3)
# 4
List.replace_at(list, 0, 9)
# [9, 1, 2, 4]

Length 3

1/2

This is an example on how to do division, the result is 0.5, to do integer division, use div function, for example div(7,2) or div 7,2 would return 3.

Length 2

?A

Question mark is one way to get the integer (or code-point) value out of a character, for this example it would return 65 as defined in the ASCII encoding.

Length 1

1

This is the example of integer literal, to check whether a variable or literal is integer, we could use is_integer function. There are virtually no limit on how big an integer can be, since it uses bignum as implementation. The limit on the VM in 32-bit platform is 536870911 bytes and 64-bit platform is 2305843009213693951 bytes, the integer creation will fail when the value are larger than those size or when not enough memory.

Factoid

iex is Elixir's interactive shell (REPL). To exit this program, press Ctrl-C twice.

\$\endgroup\$
16
\$\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
    \$\begingroup\$ Shame I didn't see this or think of it sooner. I love fortran. \$\endgroup\$ – krs013 Mar 11 '15 at 4:20
16
\$\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 25: (Mod([1,1;1,0],m)^n)[1,2]

\$\endgroup\$
16
\$\begingroup\$

Prolog

Factoid

Prolog is one of the first and most popular logic programming language.

Since Prolog is a declarative language based on first-order logic, programs in it can be surprisingly elegant, or devilishly mindbending.

“In Prolog programming (in contrast, perhaps, to life in general) our goal is to fail as quickly as possible.” — The Art of Prolog

Length 1

X

In Prolog, any identifier that starts with an uppercase letter is a variable, which initially has no value. Unlike most programming languages, variables in Prolog can only take a value once (we say that the variable gets unified with something). After unification, a variable cannot be updated (unless backtracking occurs… more on that later). Variables only get a type once they are unified (the type of what they get unified with), therefore a free variable can be unified with anything.

Length 2

X.

This is a valid query in Prolog. Unlike most languages, in prolog you run queries (like in SQL), and the Prolog execution engine will attempt to satisfy that query. In particular, it will unify variables along the way if those unifications make the query true. Each query ends with a period.

Here however, the query is not really meaningful, since we are asking Prolog to check that a free variable X is true, and it is for an infinite number of different unifications (any integer for instance would make this true). Therefore, here is what SWI-Prolog answers to that query:

% ... 1,000,000 ............ 10,000,000 years later
% 
%       >> 42 << (last release gives the question)

Length 3

nl.

In Prolog, any identifier that starts with a lowercase letter is called an atom. They can be used to name predicates, facts, or simply as string-like objects. Here, nl/0 is a predicate which has 0 arguments (hence the /0 notation) and which is a built-in in Prolog. This predicate simply prints a line break to STDOUT:

?- nl.

true.

You can see that Prolog really likes to print true. when it manages to satisfy your query (or false. when it doesn't).

Length 4

X=0.

In Prolog, = is unification. Prolog will satisty this query by unifying X with 0, which is the only possible way of satisfying it.

Length 5

X=[].

In Prolog, the list is a central data structure that you will use constantly. All lists are written in square brackets. A special list that will show up very often (particularly when writing your recursion termination condition) is the empty list, noted [].

Length 6

X=3+B.

Prolog is homoiconic, and as such the above query is perfectly valid. The REPL returns the following:

X = 3+B.

In short, we are unifying variable X with the expression 3+B (which does not get evaluated in any way). If we now unify B with something, this will be reflected in X:

?- X=3+B, B=5.
X = 3+5,
B = 5.

(As you can see, X is not evaluated to 8)

Length 7

X*X#=4

Here I am cheating slightly. To make the above work, you must first run the following query: use_module(library(clpfd)).. This is the constraint logic programming in finite domains (CLPFD) library, which allows us to do very powerful things: for instance, the REPL will return the following for the above query:

X in -2\/2.

\/ represents the union of two domains. Therefore, what Prolog is telling use here is that for X to satisfy X*X = 4 (the # in the query is CLPFD's syntax for constraints), X must be either -2 or 2.

This is a very powerful mechanism that allows to write constraints on variables, without specifying how to find the values that satisfy them. Writing something like a sudoku solver with this library is thus extremely easy: you only have to describe the constraints between cells, and the starting clues. Prolog will then find solutions for you!

Length 8

X=2;X=9.

Prolog is a logic programming language, and as such you expect to be able to use disjunctions. This is exactly what ; (Or) does: X unifies with 2 OR X unifies with 5. When running this in Prolog's REPL, we get the following:

?- X=3;X=9.
X = 3

The REPL halts after printing you this answer, instead of finishing and waiting for a new query. Indeed, Prolog thinks there are other possible answers (and there is one in this case), and so it is waiting to see if you are interested in those. By pressing ;, it will give you another answer:

?- X=3;X=9.
X = 3 ;
X = 9.

which is what we expected to get. Here, Prolog knows there are no other possible answers for what we queried, so it will finish and wait for another query.

The mechanism behind this is called backtracking: when Prolog choses to unify X with 2, it remembers that it made that choice when in fact there are other possibilities (here, unifying X with 9). When we ask for another answer (or if the query had failed after that choice), it will backtrack to the last choice it made and try another one, until no other choice is available.

Length 9

a(ax+b).

Here is a fact, that constitutes your source code. We can make some interesting queries on that fact, to check out Prolog's pattern matching mechanism (remember that identifiers starting with an uppercase letter are free variables):

?- a(X).
X = ax+b.

Cooler:

?- a(X+b).
X = ax.

Even cooler:

?- a(X+Y).
X = ax,
Y = b.

Length 12

length(L,3).

length/2 is a built-in predicate of Prolog which is true if its first argument is a list of length its second argument. Here, we are setting the second argument as a ground integer, and the first as a variable. Thus, we get the following behavior:

?- length(L,3).
L = [_G1500, _G1503, _G1506].

That is, for that query to be true, L must be a list of 3 elements; those elements are _G1500, _G1503 and _G1506 which are variables (those names are internal variable names).

We can also run that predicate with both arguments as variables, and get the following very powerful behavior:

?- length(L,M).
L = [],
M = 0 ;
L = [_G1512],
M = 1 ;
L = [_G1512, _G1515],
M = 2 ;
L = [_G1512, _G1515, _G1518],
M = 3 ;
L = [_G1512, _G1515, _G1518, _G1521],
M = 4 ;
…
\$\endgroup\$
  • 1
    \$\begingroup\$ Length 7: That's not cheating. It's explained in the CLP(FD) library documentation that users are encouraged and even expected to have :- use_module(library(clpfd)). in ther initialization file, so that CLP(FD) constraints are avilable in all programs. \$\endgroup\$ – mat May 30 '16 at 12:28
16
\$\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\$
  • 1
    \$\begingroup\$ What did you plan for the 7th snippet? \$\endgroup\$ – Erik the Outgolfer Sep 23 '16 at 10:12
  • \$\begingroup\$ the alternate fifth doesn't have the backslash \$\endgroup\$ – Destructible Lemon Oct 28 '16 at 22:39
  • \$\begingroup\$ @DestructibleWatermelon fixed \$\endgroup\$ – acrolith Oct 29 '16 at 1:00

Your Answer

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

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