TransWikia.com

Showcase of Languages

Code Golf Asked on November 19, 2021

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>

238 Answers

ErrLess

Factoid

ErrLess is a functional language where every command is one character long. Its defining feature is that it refuses to throw any errors, even if you divide by zero!

You can run ErrLess in your browser by inserting your code into the code section of this python program.

Length 1 snippet

.

Halts instantly. In ErrLess, when the instruction pointer reaches the end of the program, it loops back to the start. This means that you have to explicitly halt your programs.

Length 2 snippet

i?

A simple cat program that infinitely echoes stdin to stdout. i fetches one character of input, which is then outputted using ?, and then the instruction pointer loops back to the start.

Length 3 snippet

'A?

Prints the character A indefinitely. Why do you only need an opening quote, and not a closing quote? Simply because I thought that there is no need for a closing quote, since a character can only be, well, one character long.

Length 4 snippet

12#.

This program does not output 12, as one might expect, but only outputs 2. Remember: every command is a single character long. First one is pushed to the stack, then two, then the top value of the stack is printed as a number, then the program halts.

Length 5 snippet

e3*#.

The answer to life, the universe, and everything. This program outputs 42: a through f push 10 to 15 to the stack, and the * operator multiplies the top two elements of the stack.

Answered by Ruan on November 19, 2021

Pxem

Pxem is an esoteric language designed by "ぬこ" (now "nk."), published in 2008. Unlike many other languages, filename matters first and content is second; that is, a Pxem program consists of two strings.

0 bytes

If content is empty, calling .e is equivalent to duplicating entire stack.

1 byte

.

Every command has this prefix; this may be awkward when you want to push the character directly, on some problems.

3 bytes

01.r

My favorite idiom to push zero on filename. As filename cannot contain NULL character (usually), this would be needed.

4 bytes

XX.z

My favorite idiom to begin pseudo comment.

6 bytes

.c.c.z

My idiom to check if stack is empty or not; goes inside if stack is empty; does not otherwise.

Answered by nrgmsbki4spot1 on November 19, 2021

zsh

1 byte

a

a is not (normally) a defined command in zsh, so why is it useful? Because it generates an error message (zsh: command not found: a). Errors are a key part of zsh golfing, because it (and other languages in the Bourne shell family) is unique among practical programming languages in their error handling - almost all errors are ignored by default, which is great for golfing. Also, since errors are so easily to generate, they are also essentially the best way to implement conditionals:

2 bytes

&&

The && operator chains two commands together, but only runs the second if the first succeeds. There is also ||, which does the opposite. They are pretty much the shortest way to implement conditional expressions, because if you can make your command generate an error in some circumstances, then you can use && instead of a bulky if statement.

3 bytes

>$1

This is probably one of the most used trigraphs in my zsh answers, but what does it do?

Well, the parts in isolation are $1 is the first command-line argument, and > redirects a command to a file. But there is no command? Ah, but when no command is provided, zsh uses the value of the NULLCMD environment variable, or cat by default. Therefore, it cats all of stdin to a file named the first command-line argument. stdin is generally not the optimal input method, and therefore I don't use it often, so it doesn't generally matter what goes into the file, but it matters that the file is created.[1]

Why does it matter that we create a file? Because the shortest way to do string pattern-matching in zsh is with so-called "globbing". A glob pattern-matches to a file. I've given an overview of globbing syntax here, but it's generally the easiest and shortest way to check if two strings are equal, or check for substrings or match all sorts of patterns (especially with the --extendedglob option). You can even create patterns dynamically, like I used in my Is it a lobster number? answer.

[1] If stdin is really needed, you can use :>$1 which pipes a no-op command, or enable the --shnullcmd option which changes that cat default to a no-op

4 bytes

echo

The echo builtin prints a string, like echo hello. Pretty simple, right? But we can actually do 2 bytes better, with the <<< syntax:

<<<hello

This is called "here-string" redirection, and it's equivalent to doing echo hello | command. Like before, there is no command, however, so it's passed to cat (see NULLCMD above) and hence to stdout.

The <<< syntax has some limitations, like:

  • it only expects a single word, so some expansion/word splitting techniques don't work
  • the expression on the right is evaluated in a subshell, so assigning variables there won't take effect outside the command
  • it's not a true command, so it can't be aliased and can't always be used in some complex statements
  • if you want to print only a newline, a bare echo is one byte shorter than <<<""

...but it can be chained without command separators, like <<<a<<<b, because multiple redirections are going to cat (thanks to multIOs). This is particurlarly useful in eval "loops" (see 7 bytes)

5 bytes

set -y

Unlike most shells, zsh does not perform field splitting by default, so variable expansions almost never need to be quoted. The -y option re-enables such splitting, which is useful in some circumstances.

zsh in fact has a plethora of command-line options, most of which can also be set dynamically with set, setopt, or unsetopt; some more interesting options include:

  • -e: errors are no longer ignored, and the shell exits immediately if one happens. If you can generate errors in some circumstances, this can act like a logical AND over the program which is useful for s
  • -n: disables all command execution. Who knows why...
  • --extendedglob: enables a whole load of extra syntax goodies for globbing
  • -F: globbing is disabled. This is useful if you don't need to do any pattern matching but want to include unquoted special characters like *. Particularly useful in
  • --forcefloat: changes division in arithemtic expansions to always produce a float, even if both operands are integers
  • --cprecedences: changes operator precedence of bitwise operators in arithmetic expansions. By default they are tighter-binding than even exponentiation, and this makes them exactly as they are in C[2]

You can find the full documentation for all of these in man zshoptions.

[2] although this still isn't the most sensible, as comparison operators are tighter than bitwise AND/XOR/OR, in what may go down in history as Dennis Ritchie's greatest mistake

6 bytes

hash -d

While not so useful in , but this provides a mechanism very handy for interactive command-prompt use of zsh. You may know that ~ refers to the home directory; well now you can define more directory aliases of the form ~a. For example, hash -d a=/usr/local means that echo ~a/bin/cat will print /usr/local/bin/cat.

It might be useful in , but I haven't actually found a use for it yet outside my dotfiles.

7 bytes

{1..$1}

{1..$1} constructs a range from 1 to the input, and expands them as separate words. This alone is not too interesting, but if you put some more string around it, like x{1..$1}y, then it can create a range with the string, like x1y x2y x3y .... If you replace x and y with partial snippets of zsh code, and then pass them to the eval builtin (which evaluates strings as zsh code), you can construct ugly-looking loops, which are often shorter than using for.

8 bytes

${a/w/} 

The ${...} construct introduces parameter expansion. In the above example we are doing a text replacement on variable $a, and removing any w characters from its contents. Zsh has a pretty reasonable regex engine. Parameter expansion also does tricky things with arrays and expansion flags. Example

9 bytes

alias A=B

alias defines token aliases (in the sense of C pre-processor macros), so in the example above, A will be replaced with B in parsing. If you're using a particular construct often, this can shorten it. For example, to output a lot of stuff, you can do[4]:

alias A=repeat 1000000
alias B='A A A A'
alias C='B B B B'
C C C C echo hi

With a little syntactic trickery, you can even alias operators:

alias X='&&'
(true)X echo hi
# => hi
(false)X echo hi
# no output

[3] Actually, for normal commands alone, it's shorter to define a function: A()command $@; [4] This is by far non-optimal for the most finite output, but what ever

10 bytes

emulate sh

zsh has a built-in command to make its behaviour much more closely mirror the POSIX shell standard (and it can also emulate csh and ksh). I don't think it will ever have a use in , except maybe or , but it's another reason that zsh should be the only shell installed on your system.

Factoid

Who needs awk, sed, or half of the other core unix utils when you can write simple Zsh code like the following from the Zsh User Guide?

This chapter will appeal above all to people who are excited by the fact that
print ${array[(r)${(l.${#${(O@)array//?/X}[1]}..?.)}]
prints out the longest element of the array $array [...] This is for advanced students only (nutcases, if you ask me).

Answered by pxeger on November 19, 2021

ARM Thumb-2

Also applies to ThumbGolf, a direct superset of Thumb-2.

ARM Thumb-2 is a rather quirky RISC instruction set. It is a 32-bit architecture, but unlike most RISC instruction sets, it uses a mix of 16-bit and 32-bit instructions.

Thumb was originally a 16-bit only subset of the 32-bit ARM instruction set, created in 1998 with the ARM7TDMI. It was designed for embedded devices which either had a 16-bit memory bus or required more code density, and it was pretty impractical otherwise.

In 2003, with the release of the ARM1156T2, this was expanded to a whole new instruction set, named Thumb-2. Combining flexible 32-bit instructions with the existing 16-bit instructions, Thumb-2 was a faster, smaller, and more polished replacement for the old 32-bit ARM instruction set.

ARM is best known for its powerful addressing modes, barrel shifter, Absolutely Ridiculous Multiplier, load/store multiple, and conditional execution.

Small factoid: Thumb was a key factor in the Game Boy Advance's design. It significantly lowered the cost of Game Paks thanks to both the code density and the cheap memory bus.

Length: 4

0841 d3xx
        lsrs    r1, r0, #1
        bcc     .Lbit_not_set

lsls and lsrs are (likely) the most useful arithmetic instructions out of the original 16-bit instruction set. Many masking operations can be done in half the size with a simple shift right and testing the flags.

This tests if the low bit is set. You can also use this for bitmasks, as lsrs and lsls also set the zero flag.

Length: 6

fab0 f080 0940

Assembly:

        clz     r0, r0
        lsrs    r0, r0, #5

I learned this one from Clang.

This sets r0 to 0 if it was nonzero, or 1 if it was zero.

In C terms, it is r0 = !r0.

It does this by counting the leading zeros, which will return a value from 0-32 (with 32 meaning the register is all zero bits), then shifting right to turn 32 to 1 and everything else to 0.

Length: 4

b100 2001
        cbz     r0, 1f
        movs    r0, #1
1:

The same as above, but sets r0 to 1 if it is non-zero, or !!r0. This shows off the cbz (compare and branch if zero) instruction, and is quite literally this:

if (r0 != 0)
    r0 = 1;

Length: 6

push and pop are very useful.

b40f bc0e bc01
        push    {r0, r1, r2, r3}
        pop     {r1, r2, r3}
        pop     {r0}

This is a similar trick to the push rax; pop rdx trick in x86_64 to avoid REX prefixes, however, it is much better:

This rotates the registers r0-r3, so r0 will have r1's value, r1 will have r2's value, etc. You can do all sorts of tricks.

Length: 12

ea80 3040 ea80 4050 ea80 1040

Assembly:

        // XorShift32
        // in: state: r0
        // out: state: also r0
        // x ^= x << 13
        eor     r0, r0, r0, lsl #13
        // x ^= x >> 17
        eor     r0, r0, r0, lsr #17
        // x ^= x << 5
        eor     r0, r0, r0, lsl #5

XorShift32, with no temporary registers. This shows off the coolness of ARM's barrel shifter.

Length: 18

19e0 0269 4066 406f 4075 407c 404e ea4f
5777
        // A rather literal translation of xoshiro128+.
        // Input: r4-r7: state
        // Output: r0: result, r4-r7 modified

        // result = s[0] + s[3]
        adds    r0, r4, r7
        // t = s[1] << 9
        lsls    r1, r5, #9
        // xor all state lanes together
        eors    r6, r4
        eors    r7, r5
        eors    r5, r6
        eors    r4, r7
        // xor temp
        eors    r6, r1
        // rotl
        ror     r7, r7, #32 - 11

If Xorshift32 is too weak for your tastes, here is its cousin xoshiro128+. However, it uses most of your precious Lo registers, so it isn't practical as a sub-algorithm. ?‍♂️

It stores the state in r4-r7, and returns in r0. It clobbers r1.

Note: xorshiro64* is two bytes larger.

Length: 12

fba0 4502 fb00 5503 fb01 5502
        // Standard 64-bit to 64-bit long multiply:
        // input: x[0]: r0, x[1]: r1, y[0]: r2, y[1]: r3
        // output: product[0]: r4, product[1]: r5
        // {r4, r5} = (u64)x[0] * (u64)y[0]
        umull   r4, r5, r0, r2
        // {r4, r5} += (x[0] * y[1]) << 32
        mla     r5, r0, r3, r5
        // {r4, r5} += (x[1] * y[0]) << 32
        mla     r5, r1, r2, r5

A 64x64 multiply with a 64-bit result. This shows off the multiply and accumulate instruction, but it gets better:

Length: 16

fba2 4500 fba2 6201 fbe3 6560 fbe3 2561

Commented assembly:

        // Does an unsigned 64-bit to 128-bit long multiply
        // in: x[0]: r0, x[1]: r1, y[0]: r2, y[1]: r3
        // out: product[0]: r4, product[1]: r6, product[2]: r2, product[3]: r5
        // {r4, r5} = (u64)y[0] * (u64)x[0]
        umull   r4, r5, r2, r0
        // {r6, r2} = (u64)y[0] * (u64)x[1]
        umull   r6, r2, r2, r1
        // {r6, r5} = (u64)y[1] * (u64)x[0] + r6 + r5
        umaal   r6, r5, r3, r0
        // {r2, r5} = (u64)y[1] * (u64)x[1] + r2 + r5
        umaal   r2, r5, r3, r1

This is a 64-bit to 128-bit unsigned long multiply. On a 32-bit processor. In four instructions. x86 takes about 30.

See my comment in xxHash's source code of the C algorithm which explains this.

Answered by EasyasPi on November 19, 2021

Arn

Arn is a golfing language I designed recently. It's a functional paradigm with variable-based storage, and has a few cool features I enjoy. The full syntax can be found by clicking the name at the top of this post. An online interpreter can be found here for those interested.

Features

Type casting

Arn will automatically cast types based on the following:

  • Arrays casting to Strings or Ints will take the 0th element.
  • Strings or Ints casting to Arrays will split on every character OR every space if there are any.

Assumptions

The variable _ will be automatically assumed in any place where one a value is missing but required.

Similarly, any closing ), ], }, ", ', or ` can be ignored if it reaches the end of an expression or the program.

STDIN

STDIN will automatically be assigned to the variable _ at runtime. It will be a string if STDIN is one line, or an array split on newlines otherwise.

Functions

Since functions exist in this language, and that means a Standard Library can exist! You will see example functions for that later.

Packing

In order to help Arn compete with other, golfing languages, a packed form exists. This form is shorter, encoded based on a modified CP1252 found here. The average compression rate, as far as I've found, is ~17%.

I am very happy with the encoding, I spent hours and hours on it. It may change to become every more concise in the future (if possible, and if I can figure out how) but until then, this will be how it works.

The interpreter can run Carn (Compressed Arn) and regular Arn without any indication of which is passed.

Compressed Strings

Should be pretty self explanatory. They are based on a dictionary found here.

The code is F * 100 + S OR F * 100, depending on if 1 valid compressed character or 2 are passed. Compressed strings are denoted with either ' or `, where the former capitalized every word and the latter just the first. You can find a full description on the GitHub page, linked at the top of the post.

Showcase

From top to bottom.

1 byte

_

This is a very simple program, it will just return STDIN. Output is implicit in this language.

2 bytes

+4

This program will add 4 to STDIN and return it. The same as saying _ + 4

3 bytes

4,7

Above features the use of an infix; specifically, the , infix. This infix is the pair verb; it takes the left and right argument, turning them into an array.

5 bytes

.fact

This little snippet shows us two new features (three, really!): the . infix, the fact function, and implicit casting. Since no value is passed to the . fix, it assumes _ on the left. This is then passed to the factorial function. The factorial function uses the 1-range fix, which takes an integer, and so _ is automatically casted to an integer.

7 bytes

+{+1}~

This showcases the extremely useful prefix. This prefix operates as both a fold and map fix; it will map using the block preceding it (if provided) and then fold with the fixes preceding that. This snippet also shows the 1-range fix, ~, in action.

Essentially, this program takes a number on STDIN. It creates a range, from [1, n] (where n is the input). Then it maps over this range, incrementing each entry by one. Finally, it adds all of the entries together.

Answered by ZippyMagician on November 19, 2021

Integral

Integral is a stack-based golfing language I recently made. It uses code page 437.

An interpreter.

1 byte

V 

Integral has many built-in functions. V reverses the top of the stack. Integral pushes all input to the stack and implicitly outputs the stack seperated by newlines.

12 bytes

÷▓ll▄å▒▌«s»÷

You can compress strings in Integral. This ouputs hello there person. Compressed strings are started and ended by ÷.

37 bytes

♂⌡ ⌡♦⌡_⌡g►⌡/⌡•⌡ ⌡g►⌡⌡►•⌡|⌡♦⌡ ⌡g►⌡|⌡►

This is an example program that takes an integer as input, and returns an ASCII-art rainbow with width n.

I do not think Integral is Turing-Complete yet.

Answered by nph on November 19, 2021

1+

I know the restriction is relaxed now but I "wanted" to follow the old rules, because 1. I'm lazy 2. I want people to care about it

And yes I do have more (currently hidden from the rest of the wrodl) snippets I'll post them if you upvote

Factoid

1+ is a fun deque-based language (although it's often referred to as a stack-based language). 1 is the only literal and, furthermore, we only have + and * but not - or /, which makes some 1+ programs fairly hard to write. (Or probably I'm just not particularly clever whatever) It's still, however, easier to use than most Turing tarpits.

1 byte

1

The only literal in 1+. Almost no program can be built without it.

2 bytes

1+

Yay, language name! It increments the top of the stack. This is where the name of the 1+ chatroom, "increment", come from. It's non-trivial to decrement the top of the stack, however.

3 bytes

"<*

Damn community wiki, I don't even know when I was upvoted... until now.

This snippet features the < operator. It's the only comparison operator in 1+, and returns the boolean value a <= b (where b is the stack top and a is the number behind it). Also, " duplicates the top of the stack and * multiplies the top two numbers.

This snippet pops the stack if the stack have at least 2 numbers. (It is impossible to get back to an empty stack without outputting.) Because a <= a is always true it replaces the stack top with 1. Then the multiply operator get rid of that 1 since a * 1 = a.

4 bytes

1+1<

Inverts the top of stack. (That is, if the stack top is 0 replace it with 1, otherwise replace it with 0.) This actually turned out to be quite useful in some places, for example dealing with 1+ control flow.

It works by computing a + 1 <= 1 and not a <= 0 since pushing a zero is 5 bytes 11+1<.

5 bytes

(|())

Infinite recursion. This is a function definition, but functions are executed once when they are declared in 1+ (very golfing-friendly).

The function declaration syntax in 1+ is (name|code) and it is called with (name). Here the name of the function is empty and it calls itself repeatedly.

7 bytes

(|"<##)

I don't have anything for 6 bytes, so here you go. This is a pop function that works anywhere (unless the stack is empty, of course). It's here to showcase the # instruction (The only other place I remember using this function is the input template) which is the only type of control flow. It pops a number n, and jumps to the instruction after the nth #. (It is 0-indexed, which is sometimes really annoying when golfing but sometimes, not so much.)

Functions creates "seperate lines of execution" according to original specs - this confuses lots of readers! Interpreter-wise, when executing a function, the interpreter calls itself. This means all # outside the function are ignored and the indexing starts from 0 again. (And all # inside the functions are ignored in the main line, that's what was meant by seperate lines of execution.)

This snippet creates a function with an empty name (because functions are executed once when they are declared, there are no need to call it). New function definitions overrides old definitions, so it will always work.

"< replaces the top number with 1, the original value doesn't matter, much like the 3 byte snippet. The following # pops a number, in this case it is 1, and jumps to the second # (don't forget it's 0-indexed!) so the 1 is gone. Then we reached the end of the function.

Answered by null on November 19, 2021

International Phonetic Esoteric Language

Factoid

The International Phonetic Esoteric Language, or IPEL, is a stack-based esolang where the instruction set mostly consists of characters from the International Phonetic Alphabet, and some ASCII.

IPEL is an attempt to apply stuff I've learned from some CS courses since starting college, as well as to create a language for myself for code golf.

Length 1

1

IPEL has 3 types: numbers, strings, and lists. Numbers from 0-9 can be pushed in by using the digit.

Length 2

io

A simple cat program. i takes a string from STDIN, then outputs it with o.

Length 3

"a"

Pushes the string a.

Length 4

1esø

This code increments the loop index by 1. In IPEL, loops are not handled by the interpreter; the programmer has to manually set the loop index. Loops also only check for when $index lt end$, where when true, jumps back to the start of the loop.

Length 5

<f>/

An empty function definition.

Length 6

{12.34}

This is how you push a float and any numbers larger than 9. Surround it in curly brackets.

Length 7

|a|ɔ|a|

Labels also exist in IPEL. When execution hits ɔ, it will jump to the label specified right after the ɔ. This is also the shortest infinite loop you can do in IPEL.

Length 8

"C"ʁ2zχo

This is my answer to the "A Without A" challenge. It pushes C, converts it to a number, subtracts 2, converts it back to a string, and prints.

Length 9

{zzzzzzz}

IPEL since v1.4.0 includes the ability to push base 36 numbers. zzzzzzz is equivalent to 78364164095 in base 36.

Length 17

<f>/1ue2sø<f>2u3u

This is the shortest program that demonstrates changing the return pointer of a function call. Without e2sø, this would print 123. With it would print 13 instead, completely skipping the 2 instructions 2u. I'm not sure if there's any practical use for this, but it's a thing you can do.

Answered by bigyihsuan on November 19, 2021

dotcomma

Dotcomma is a simple esolang I made, which uses only 4 instructions and is not Turing complete is now Turing complete, due to the addition of a queue for storage.

Factoid:

With only the instructions [.,], the . and , operators are heavily overloaded. For example, , can take input and output, manage the queue, test the number of times a code block was evaluated, and conditionally evaluate a code block. Which of these occur is decided by what characters precede and follow an operator.

Length 2 snippet:

All dotcomma programs are wrapped in code blocks ([]), so a length 1 snippet is impossible.

[]

This program does nothing.

Length 3 snippet:

[.]

This program sets its return value to 1. All operators and blocks have a return value, which can be used by other operators and blocks to nest expressions, create loops, or manage the programs's structure. If the . operator is preceded by [, it's return value is 1. If followed by a ], it uses its return value as the block's return value.

Length 3 snippet:

[,]

This program would previously take a value from input, and output it. The return value of the , operator would have been taken from input when preceded by [, and outputted if followed by ].

In "modern" dotcomma, this will take a value from the queue, and place it at the end of the queue. For example, given the input 6 7 8 (input is placed on the queue by default), this program would output 7 8 6 (final value of the queue is used as output by default).

Like the . operator, , will use its return value as a block's return value if followed by ].

Length 4 snippet:

[.,]

This program will output 1. As with the second snippet, the .'s return value is set to 1. However, because the , operator is preceded by an operator, it will use that operator's return value instead of taking a value from the queue.

Length 5 snippet:

[[,]]

This program will take a value from the queue, and place it back on the queue. However, it will have a return value of 0. This is because the , is wrapped in a nested block, and blocks default to a return value of 0 if an operator does not explicitly define one.

Length 6 snippet:

[[,].]

This program does the exact same thing as [,]. The . operator, if preceded by ], will set its return value to the sum of the return values of all previous un-separated blocks, which is only one in this case.

Length 9 snippet:

[[].[],.]

This will return the -1. The first empty block's return value will be read by ., which returns 0. As a result, the next block will be skipped (a loop that runs 0 times). Because the block preceding the , was never run, its return value will be -1.

Length 11 snippet:

[[,.][,.].]

This program uses the . operator's addition capabilities to take the sum of two inputs and use it as the program's exit code. Adding a . to the end of the , operators will prevent them from outputting, as they are no longer followed by ].

Answered by Redwolf Programs on November 19, 2021

W

Factoid

W is a simple stack-based golfing language that is surprisingly very concise. Its powerful iterator protocol and implicit input system is the cause for this.

Length 1

w

This is in fact a valid Truth-machine program (infinite 1 while 1). Let's explain it. The first step of the execution is to prepend all of the possible inputs to the stack:

aaw

Note that the input is used both as the condition and as the body of the while loop. Therefore this program decodes to the following pseudo code:

while the input:
    print the input

The print is implicit in every while iteration. So if the input is 1 (a truthy value), this prints the input 1 indefinitely.

You might want to ask, could this code snippet produce the right result for a 0 input? Yes; the while loop returns the condition onto the stack after the execution, therefore 0 is outputted onto the stack.

IMPORTANT NOTE. W's while loop is only for demonstration purposes. Never use this instruction, because W is designed to allow users to use for loops over while loops.

Length 2

+M

The W snippet that I am most proud of! It showcases more of W's powerful protocol.

So let us first try to make 'z' (the string) as an input. The program outputs:

aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz

Well, you might be confused by this odd output. Don't worry; I will explain it.

aaa+M

This transpiles to:

map(a,a+a)

Which means double every item in the string. If the string was 'ab' then the output would be 'aabb'.

So, why in the world would it return the doubled alphabet? Well, the Map instruction has an automatic range that allows users to iterate over a singleton. (Because it is pointless to do so)

In this context, this will return a range from lowercase a to z, hence the doubled alphabet.

Answered by user85052 on November 19, 2021

평범한 한글(Unsuspected-Hangul)

Unsuspected-Hangul is functional esolang.

Factoid

Unsuspected-Hangul only uses 10 consonants of Korean character : ㄱㄴㄷㄹㅁㅂㅅㅇㅈㅎ, and other consonants are replaced by them. Vowels and final consonants are dismissed. Non-hangul(alphabet, number, white spaces) are all same.

Rule of replacement

ㅊ -> ㅈ, ㅋ -> ㄱ, ㅌ -> ㄷ, ㅍ -> ㅂ
ㄲ -> ㄱ, ㄸ -> ㄷ, ㅃ -> ㅂ, ㅆ -> ㅅ, ㅉ -> ㅈ
ㄳ -> ㄱㅅ, ㄵ -> ㄴㅈ, ㄶ -> ㄴㅎ, ㄺ -> ㄹㄱ, ㄻ -> ㄹㅁ, ㄼ -> ㄹㅂ, ㄽ -> ㄹㅅ, ㄾ -> ㄹㄷ, ㄿ -> ㄹㅂ, ㅀ -> ㄹㅎ, ㅄ -> ㅂㅅ

You can try unsuspected-hangul here

Length 1

ㄱㄴㄷㄹㅁㅂㅅㅈ is number : From zero to seven.

Only initial consonant counts : so it is same as , So it returns 0.

강 means river.

Legnth 2

나무

Even-length number is negative, while odd-length number is positive. Every number is octal.

ㄴ is 1, and ㅁ is 7, and it is written backward, so ㄴㅁ is -71(octal), -33(decimal).

나무 means tree.

Length 3

코끼리

This is odd-length, so it is positive. It is equivalent of ㄱㄱㄹ, 300(octal), and 192(decimal).

코끼리 means elephant.

Length 4

집전화기

Now introducing : types. Unsuspected-hangul has 7 types : Number, Boolean, String, List, Closure, IO, Nil.

ㅈㅈ is built-in function that returns True. And ㅎㄱ calls function with 0 parameters. So ㅈㅈㅎㄱ returns True.

집전화기 means Home telephone.

Length 5

문자 한개

Non-hangul(like space) right before can be omitted. ㅁㅈ is built-in function that changes number to string (if given with parameter). If ㅁㅈ called with no parameter, it just returns empty string.

So ㅁㅈ ㅎㄱ returns ''

문자 한개 means One character.

Length 6

평범한 한글

Yes, It is name of the language. It is equivalent of ㅂㅂㅎ ㅎㄱ.

makes function. ㅂㅂ ㅎ( is ㅂㅂㅎ) is function that returns -45.

ㅎㄱ calls function with no parameters, so it returns -45.

평범한 한글 means Ordinary Korean character, or Unsuspected Hangul.

Length 7

또 또 신호등

ㄷ ㄷ ㅅㅎㄷ. is built-in function for power. ㅎㄷ calls function with two parameters. (Remember ㄷ means 2?)

So it calculates 2^2, and returns 4.

또 또 신호등 means Traffic light again again.

Length 8

나 과제 다했다

ㄴ ㄱㅈ ㄷㅎㄷ. is built-in function for addition. ㄱㅈ is -56, so it calculates 1 + (-56), and returns -55.

나 과제 다했다 means I'm done with my assignment.

From github readme.md file.

Length 9

그는 자는 척했다

ㄱㄴ ㅈㄴ ㅈㅎㄷ. is built-in function for comparison. If first parameter is smaller than second parameter, returns true. ㄱㄴ is -8, and ㅈㄴ is -15. So it returns False.

그는 자는 척했다 means He pretended to sleep.

Answered by LegenDUST on November 19, 2021

Keg

Factoid

Keg is a stack-based golfing language, created by PPCG user Lyxal, that focuses on simplicity and readability. It is fairly unique compared to most other golfing-based languages, since it has few instructions, and alpha-numeric characters are automatically pushed to the stack. It also has implicit input and output.

Length One

"

An example of the stack controls in Keg. This rolls the stack, which puts the top of the stack to the bottom. It is the opposite of ', which rolls the stack in the opposite direction, putting the bottom of the stack at the top.

Length Two

ab

Since these are alpha-numeric characters, they get auto-pushed to the stack as their respective ASCII values, which in this case are 97 and 98.

Length Two (bytes)

ߞ

Since this is not an instruction, this will be pushed onto the stack automatically. Keg allows Unicode characters to be pushed onto the stack, so this pushes 2014.

Length Three

83*

Any numbers get auto-pushed to the stack. In this case, it pushes 8, then pushes 3, and then multiplies them, giving 24.

Length Four

¿:+.

This shows how duplicating items and integer printing works by using nice input (evaluation of input) to double the given number.

Length Five

[a|b]

An example of an if statement in Keg. When an if statement is run, the top item of the stack is popped. If it is non-zero, the left code is run, whilst if it is zero, the right on the right is run. Note that the right side is optional

Length Six

(56*|1

An example of a for loop in Keg. The number on the left side is how many times it'll run, whilst the code on the right is what's run. In this case, it pushes 1 to the stack 30 times. If the left side isn't specified, it will automatically be the length of the stack. Also, all ending brackets get automatically completed at the end of the program, making this valid.

Length Seven

{!4>|.}

An example of a while loop in Keg. The code on the left is the condition, and the code on the right is what's run. In this case, while the length of the stack is greater than 4, it outputs the top element of the stack as an integer.

Length Eight

 
& &:.& 

This demonstrates a unique features of escaping characters and accumulator usage. The instruction escapes the newline, which has an ASCII value of 10, then the accumulator is set to 10. After that, the accumulator value will be accessed and printed, resulting in the program printing 10.

Length Nine

`Snippet`

This demonstrates the usage of strings in Keg. It pushes the string "snippet" and prints it.

Length Eleven

^!~$%(_|")_

This showcases most of the commands in one concise program. This removes exactly 1 character from 1 line of input randomly.

Length Twelve

@d1|:+ƒ¿@dƒ.

This defines a function called d and assigns the code :+ to it (doubling the input passed to it). Nice input is then taken (¿) and d is called on the input.

Keg Related Links

Esolangs Page

Official Github

Try it Online!

Keg Chatroom

Answered by EdgyNerd on November 19, 2021

Pyramid Scheme

With all the scheme dialects out there, I suppose it was inevitable that a Pyramid Scheme should arise. Created in early 2017 by our very own Conor O'Brien, this 2D esolang does in fact read very much like Scheme!

Length 1

^

This little guy is the start of everything. The tip of a pyramid. Without the caret, there can be no Pyramid Scheme. On its own, though, it's not a valid program; you've gotta rest the pyramidion on something...

Length 3

^
-

There it is. A full pyramid, complete with base and capstone. This 3-byter is the shortest program that will not error; it prints 0 followed by a newline and terminates gracefully. What it's really doing is accessing the default value of the variable-without-a-name; more on variables later, once we have larger pyramids.

Length 4

​
^
-

Exactly as before, but now with a leading blank line! This program does nothing; it is the shortest possible program of the sort. Execution in Pyramid Scheme always begins on the first line. Each pyramidion on that first line is evaluated, and then the results are printed with linefeeds between if nothing has yet been printed. As the first line here is blank, nothing gets evaluated or printed.

Length 5

^^
--

On the other end, here's a program with more than one pyramid at the top. The one on the left will be evaluated first (yielding 0, as in the length-3), followed by that on the right. The results are collected in a list during execution; once all evaluation is complete, since nothing has yet been printed, the results are dumped to stdout:

0
0
​

Answered by Khuldraeseth na'Barya on November 19, 2021

Author's note: While more snippets have been prepared, I will honor the original restriction somewhat and wait for interest. EDIT: It's been months, and I suddenly realized I have a bunch of examples I haven't posted. I'd hate for them to go unshared, so here they are now. (new examples start at 16 bytes)

Zsh

Zsh may seem like a new language, given the (relatively) recent popularity of the "Oh My Zsh" framework, but it in fact dates back to 1990, just one year after Bash released. Zsh's syntax is inspired by the bourne shell and ksh.

Many people are familiar with Bash scripting, but don't understand how Zsh differs. Zsh brings a surprising amount of powerful constructs. I'll be highlighting these differences here.

Length 1 Snippet

:

This is equivalent to the command true. It returns zero (truthy in shell scripts). Uses for this include short bodyless for loops: for ((x;y;z)):

Length 2 Snippet

$a

Parameter expansion. If a is set to some value, substitute that value.

Unlike in Bash and POSIX shells, if $a is an array, this will expand to all non-empty elements (or, in the language of shells, "words") of $a.

Length 3 Snippet

$=s

This is equivalent to the expansion ${=s}, which induces word splitting. For parameter expansion forms that involve a prefix (except for flags, see below) or modifiers (see below) the surrounding braces can be removed if unambiguous.

Unlike in Bash and POSIX shells, word splitting is not done on parameters by default. To split on $IFS, this construct is needed, or the option shwordsplit needs to be set.

Length 4 Snippet

*(.)

When expanding globs, Zsh supports glob qualifiers specified in parentheses after the glob. Appending (.) as above will cause this glob to expand to all regular files in the directory. There are dozens of globbing qualifiers, here are just a few:

  • /: Directories
  • F: Non-empty directories
  • @: Symlinks
  • U: Files owned by the effective UID
  • Yn: When n is a number, expand to the first n matches.

Length 5 Snippet

${~x}

This will expand x as a glob. This is useful to match filenames, match case expressions, and in [[ tests.

Length 6 Snippet

${s:l}

Zsh supports various modifiers to parameter expansion. The l modifier will lowercase all words of s. The equivalent construct in bash is "${s,,}" (or if s is an array: "${s[@],,}".

Other useful modifiers include:

  • a: Turns paths into absolute paths
  • A: Turns paths into absolute paths with symlinks resolved
  • s/foo/bar: Does replacement on each element. Use gs/foo/bar for global replacement.
  • &: Repeat the previous substitution.

Length 7 Snippet

${(i)@}

Zsh also supports roughly 30 parameter expansion flags. The i flag will sort the parameters case-insensitively.

  • k: Substitute the array keys instead of values
  • P: Induce indirect parameter expansion: if a='b' and b='c', then ${(P)a} expands to 'c'
  • q: Quote characters special to the shell with backslashes or $'NNN'. q- and q+ will use different methods for quoting.
  • u: Remove duplicate words in the expansion.
  • z: Split into words according to shell parsing grammar: if c='"a b" c', then ${(z)c} will split into "a b" c.

Length 8 Snippet

xy${^a}z

With this expression, if a is some array (e.g.: a=(hello world)), a is converted to a brace expansion (e.g.: xyhelloz xyworldz

Length 9 Snippet

<<<${str}

Like in bash, this is a here-string. Unlike in bash, if no command is provided, the string is printed to stdout. This can often be used as a replacement for echo, except that the expansion of ${str} occurs in a subshell.

Length 10 Snippet

$a[(r)a?*]

Array subscripts also have flags! r is "reverse subscripting": This will give the first word in a whose value matches a?*. (Likewise, R gives the last match.)

Other flags include i and I which return the indices or keys of the match, k and K which match the keys, or w or f which split scalar a on words or lines, respectively.

Length 11 Snippet

b=(${@:*a})

This is another form of parameter expansion, it will expand to all words of "$@" that exist in the array a. Similarly, ${@:|a} will expand to the words of $@ which do not exist in a.

Length 12 Snippet

${${(f)s}:h}

One of the most powerful features of Zsh is that parameter expansions can be indefinitely nested. So this will take s, split it on newlines, and then strip each line's the last path component. (/usr/bin/zsh/usr/bin)

Length 13 Snippet

$argv[i,i+10]

The numbered parameters $@ can also be found under the named array argv. For some purposes, this can be more convenient or more consistent if also working with other arrays.

There are two ways to get a substring or non-associative array. The ${name:offset:length} method works the same way in Bash, but the $name[start,end] method is different: The subscripts use arithmetic expansion, like you'd find in $[ ] or $(( )).

Length 15 Snippet

print -P %D{%F}

Like Bash's PS1 sequences, Zsh has its own prompt sequences. %D expands to the current date, with an optional {string} after it. That string will be passed to strftime to be expanded.

Variables can also be prompt-expanded with the % expansion flag: ${(%)foo}

Length 16 Snippet

<<<$[[#16]8#755]

Arithmetic expansion supports any base from 2-36 (inclusive). n#... will interpret the number at that base, while [#n] will return the number in that base.

The number will be printed as base#number (this example: 16#351) with the exception of certain options and bases:

  • setopt nocbases: No special cases
  • setopt cbases: Base 16 numbers will be printed as 0x[num]
  • setopt cbases octalzeroes: Base 8 numbers will also be printed as 0[num].

With setopt octalzeroes, numbers with leading zeroes in arithmetic expansions will be interpreted as octal, without needing the 8# prefix.

Length 19 Snippet

setopt extendedglob

This deserves a post on its own... This option adds a lot of new globbing options. It's like changing from EREs to PCREs, but with globs. I've started submitting zsh -oextendedglob as a language for some challenges.

Length 29 Snippet

for x y (${a:^^b})c+=$[$#x+y]

Okay, there's a lot here. This will:

  • ${a:^^b}: Zip the arrays together, looping the shorter of the two arrays.
  • for x y (...): Pull words out two at a time, assigning them to x and y
  • b+=($[$#x+y]): Add the length of x to the value of y, and append that to c.

Because only one operation is done for each iteration of the loop, no { } or do done is needed.

Answered by GammaFunction on November 19, 2021

Attache

Factoid: This language originally started out as a joke, based on the "Mathematica has builtins for everything"; this can be seen by the residual Rot command, made for Rot13 and similar challenges.

Length 0 snippet

The empty program is valid in Attache. Try it online!

Length 1 snippet

V

Try it online! The V function was one of the first implemented. It represents a Vector of values, and used to be the only way to create array literals.

Length 2 snippet

`+

Try it online!

This is a quoted operator; it acts just as a function which performs addition. It can be assigned like so:

f := `+
Print[ f[1, 2] ]
?? prints 3

Length 3 snippet

1:9

Try it online! This is a demonstration fo the range operator in Attache. Attache's main focus resides in generation and selection, as is common with functional languages.

Length 4 snippet

Bond

Try it online! Bond is a function used to partially call functions. In this case, Bond[f, n] returns a function which takes arguments ...x and calls f[...x, n]. In the link, this is shown by example:

f := Bond[`/, 1]

This function returns a function which returns the reciprocal of the input. This is roughly equivalent to the lambda:

{ _ / 1 }

…but we'll get to that next.

Length 5 snippet

{_2-_}

Try it online! This is a lambda function, which can be called with any amount of arguments. These arguments are accessible using blanks, with _N referring to the Nth argument, starting at _1. _ is short from _1. So, this function can be written as:

{ _2 - _1 }

This is the 1st argument subtracted from the 2nd. In the example, we assign this function to f. Then, f[3, 6] is 6 - 3, which evaluates to 3.

Length 7 snippet

Print!7

Try it online! This shows the operator form of !, which takes a function on the left and an argument on the right. It's equivalent to function calling. This calls the inbuilt Print function with input 7, which outputs 7.

Length 8 snippet

~{-_'_2}

Try it online! This demonstrates a few more operators in Attache. First, ~, when used functionally, reverses the operands given to a function. So, for example, (~V)[1, 2, 3] would be called as V[3, 2, 1], which gives [3, 2, 1]. ~ has the effect of reversing the order in which abstracts are called. The above function could be rewritten as:

{-_2'_}

Now, the ' operator, when used on data, concatenates them. Since - is unary, it negates _2. This is equivalent to:

{ [ -_2, _1 ] }

Assign it as f, and f[1, 2] becomes [-2, 1].

Length 9 snippet

{Sum!_&_}

Try it online!

& when using data, a&b, creates an array of a copies of b. So, _&_ creates _ copies of _. 4&4 is, for example, [4, 4, 4, 4]. Then, Sum is called on that array. Thus, this squares a number.

Answered by Conor O'Brien on November 19, 2021

Bitwise Cyclic Tag

Factoid:

Bitwise Cyclic Tag is a programming language with only two commands, 0 and 1. It operates on an unbounded tape of bits and is somehow Turing-complete...? I don't yet understand this, but I'll be learning the language along with all of you. Bitwise Cyclic Tag is incredibly simple, even compared to brainfuck and other Turing tarpits, making it a very useful tool for proving other languages' Turing-completeness—if it can interpret BCT, it can do anything! In fact, our very own Ørjan Johansen did just this to prove /// Turing-complete in 2009, writing this interpreter.

Length 1 snippet

0

This here is half of the language. When a zero bit is encountered in the code, the first bit of the data tape is discarded (some implementations print it as well). That's it.

This program demonstrates an important feature of BCT: the code is not run just once, but over and over until the data tape is empty (hence, "cyclic"), at which point execution halts. Therefore, this 0.125-byte program can be considered a sort of cat program, as in any implementation that prints on discard, this will print the entire starting data tape in order and exit gracefully.

Length 1 snippet

1

This here is the other command in BCT. It's a touch more complicated. When a one bit is encountered in the code, if the first data bit is a one, the following bit in the code is appended to the data (on the end). If the first data bit is a zero, nothing happens. In either case, the bit in the code immediately following the 1 is skipped.

It is worth noting that I was not completely honest about repeated execution in the first snippet. The code is treated as a loop (think Haskell's repeat), so if this snippet is executed, the bit possibly written is the 1 itself. This snippet, then, will infinitely add ones to the end of the data if the tape starts with a 1 or do nothing forever otherwise.

Answered by Khuldraeseth na'Barya on November 19, 2021

Stax

Stax is a stack-based golf-oriented language. That's a pretty crowded space, but stax has a few novel properties. There's an online interpreter.

Two stacks

There are two data stacks, "main" and "input". The language name is inspired by this. Normally standard input starts on the input stack, split into lines. Most operations operate on the main stack. However, if the main stack is empty, read operations fall back to the input stack instead.

Types

Falsy values are numeric zeroes and empty arrays. All other values are truthy.

  • Integer Aribitrary size
  • Float Standard double precision
  • Rational Fractions of integers
  • Block Reference to unexecuted code for map/filter/etc
  • Array Heterogeneous lists of any values

Compressed string literals

Stax has a variant of string literals suitable for compressing English-like text with no special characters. It is compressed using Huffman codes. It uses a different set of Huffman codes for every pair of preceding characters. The character weights were derived from a large corpus of English-like text. "Hello, World!" could be written as `jaH1"jS3!`. The language comes with a compression utility.

Crammed integer arrays

Similarly to compressed string literals, stax also has a special feature for efficiently representing arrays of arbitrary integers. It uses almost all the printable ascii characters. It uses the information in each character efficiently to embed how long each integer is, and their values. This feature is new in Stax 1.0.6.

Debugger

Stax has a web-based development and execution environment. It runs entirely client-side with no ajax calls. It features a step-through debugger that shows the current state, including all registers, stacks, and current instruction. |` is a programmatic break instruction. There is also a C# GUI and CLI for Stax.

PackedStax

PackedStax is an alternative representation for Stax code. It is never ambiguous with Stax, since PackedStax always has the leading bit of the first byte set. That means the same interpreter can be used for both representations with no extra information. For ease of clipboard use, PackedStax can be represented using a modified CP437 character encoding. It yields ~18% savings over ASCII.

Rationals

Stax supports fraction arithmetic. You can use u to turn an integer upside down. So 3u yields 1/3. Fractions are always in reduced terms. 3u 6* multiplies 1/3 by 6, but the result will be 2/1.

Implicit input eval

Normally the text in the input starts in the input stack. The stax runtime can parse input into stax data structures. This is rather convenient for many PPCG posts, where input formats are flexible. This happens only when certain conditions are met.

  • Input contains no newlines
  • Parsing input succeeded. Support types are integers, floats, rationals, strings, and arrays.

For example, this input would be parsed into corresponding values on the input stack.

1 2.3 [4/5, "foo"]

Examples

Snippet: Length 0

An empty program in stax will reduce a fraction. This is the result of automatically evaluated input, and a built-in rational type. Rational values are always in reduced terms. And since there's no explicit output in the program, the top of the stack is implicitly printed.

Run and debug it

Snippet: Length 1

A one character stax program can filter out the blank lines from standard input. f is generally used to use a block to filter an array, but when it's the first character of a program, it uses the remainder of the program to filter the input lines. The rest of the program is blank, so the filter is an identity filter, and blank lines are falsey.

f

Run and debug it

Snippet: Length 2

This program iterates over the positive integers from 1 to n and adds them.

F+

Run and debug it

Snippet: Length 3

This program gets the first n letters of the alphabet. Va is the lowercase alphabet. ( truncates to the specified input length.

Va(

Run and debug it

Snippet: Length 4

In 4 bytes, you can use a block to map each character to its ascii code in hexadecimal. There aren't strings per se in stax, but arrays of character codepoints are treated as strings in many contexts. {...m establishes a block and maps every element in an array using the contents. |H converts a number to hexadecimal.

{|Hm

Run and debug it

There is also a length-4 proper quine in Stax, which is quite different from how most proper quines are constructed.

..SS

Run and debug it

. is the leading character for a two-character literal and ..S is the string literal ".S". S builds the powerset of the array, excluding the empty set, i.e. [".",".S","S"]. The result is then implicitly flattened and output.

Answered by recursive on November 19, 2021

Pain-Flak

Pain-flak is brain-flak's evil sibling, I would just read the docs here

6 Bytes:

))((}{

That pushes 1 to the stack (stack clean)

156 Bytes:

><))))))))))))()()()((}{(}{(}{)((((}{}{)((][][][][(][][(]][[)((]][][][][][[)(()‌​])][)][(][][}{([)()()()]][[))])()()([)])][][][([))))}{)((}{(((}{}{(((((}><{

The hello world program made by Dennis (run with -A)

Answered by Christopher on November 19, 2021

Triangularity

Factoid

Triangularity is a minimalistic esolang, which can (for now) only perform very basic arithmetic and string / list manipulation. As its name might suggest, every piece of code should be padded nicely with triangles of dots. Valid Triagularity programs must have the character count listed in OEIS A056220 (except for -1), otherwise you are probably doing something wrong.

Length 1

)

This just pushes a 0 onto the stack, and the top of the stack is implicitly outputted.

Length 7

.).
IEp

First off, ) pushes a 0 onto the stack, the argument to I, which retrieves the 0th line from STDIN. E evaluates it to an integer and finally p tests our integer for primality.

Length 17

..)..
.IE).
@IE+.

Adds any two valid inputs, either numbers or collections.

Length 31

...)...
..IE)..
.0>)@_.
^)IE/..

Computes the absolute value of a number, by multiplying by its sign, with a few tweaks.

Length 49

....)....
...2)1...
../D)IE..
.^is)@IE.
^i=......

Checks if the integer part of the square root of two numbers given as input is identical.

Length 71

..... .....
...."!"....
..."ld"+...
.." Wor"+..
."Hello,"+.
...........

Of course, we need a "Hello, World!" program! This can actually be golfed down to 49 bytes

.... ....
..."!"...
.."ld"+..
." Wor"+.
"Hello,"+

Try it online!

Answered by Mr. Xcoder on November 19, 2021

The Lambda Calculus

Factoid:

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

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

Length 1:

x

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

Length 3:

f x

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

Length 4:

λx.x

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

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

Length 4:

λx.y

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

Length 5:

f x y

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

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

Length 7:

λx.λy.x

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

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

Length 7:

λx.λy.y

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

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

Length 7:

λf.λx.x

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

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

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

Length 8:

(λx.x) y

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

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

Length 9:

λf.λx.f x

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

Length 14:

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

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

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

Length 12:

λp.p λx.λy.x

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

Length 12:

λp.p λx.λy.y

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

Length 18:

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

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

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

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

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

Length 30

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

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

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

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

Answered by Khuldraeseth na'Barya on November 19, 2021

MY

MY currently has no implemented codepage, so code will be listed in both bytes and the unimplemented codepage, one following the other. MY is stack based and "vector oriented" (like Jelly, some commands automatically "vecify" over their arguments). MY also has an "Object Subject Verb" visual order of commands.

1 byte

27
↵

This program outputs 0 with a trailing newline. MY does not have implicit input nor implicit output, if one pops from an empty stack, it pops 0.

2 bytes

1F 27
⍞↵

This program takes a line of raw input, then outputs it (with a trailing newline). MY can't do very much in 1 or 2 bytes due to lack of implicit IO.

3 bytes

1F 64 27
⍞h↵

Reads a line from STDIN, then converts it from hexadecimal (must be uppercase) to an integer. This beats Jelly.

4 bytes

01 02 81 26
12-←

This is where the quirk of MY comes in, for multiple argument commands, MY pops the amount of arguments needed, then applies them to a function in the order that they are popped. OSV, this resembles (hence, the Y standing for Yoda). Thus, the above code outputs 1 rather than -1 (without a trailing newline).

5 bytes

01 4D 02 80 26
1W2+←

This showcases MY's "vector orientation". This differs from APL and J, but is more like Jelly's concept of vectorizing ("vecifying" in MY). The program pushes 1 to the stack, wraps that in an array, pushes 2 to the stack, adds the top two elements, then displays with no newline (outputting [3] due to the "vecification" of commands).

Answered by Adalynn on November 19, 2021

Decimal

Decimal, also called 09D by some users, is an esoteric stack-based programming language I created that uses only the characters 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, and D.

Factoids

  • Decimal is stringly typed. The PUSH code for STRING is 3.
  • Decimal was on tio.run from day 1 of its release.
  • Decimal is not based on the top of the stack. It's based on a Default Stack Index (DSI). All functions that write to the stack set this index.
  • While very obfuscated, Decimal can be easily translated into pseudo-stack code.
  • All characters other than 0-9 and D are simply printed as they appear in the source code. This excludes whitespace.
  • Decimal uses Assembly-like comment syntax, e.g. ;COMMENT.

The Decimal GitHub repo is here.

Length 1 snippet

2 is the command for POP. Simple enough. POP pops the DSI from the stack.

2

Length 1 snippet

5 is the command for IF/ENDIF.

5

If not in an if-statement, 5 will check the DSI value. If truthy, the interpreter will continue reading as normal. If falsy, it will ignore all commands until 5, except JUMP. JUMP will exit any if-statement.

If currently in an if-statement, 5 acts as ENDIF.

Length 3 snippet

Command 3 is the command for I/O. The first argument specifies where to read from (0 for stack, 1 for user input). The second argument specifies where to put the read value (0 for stack, 1 for output).

All I/O commands are 3 characters long.

Length 3 snippet

Command 9 is the command for JUMP. JUMP commands must end in the character D. JUMP 0 exits the program.

91D

If jump #1 has not been declared, 91D will declare it. If jump #1 has been declared, 91D will jump to it.

Length 4 snippet

Command 4 is the command for MATH. See the MATH section in the Decimal README for more information on MATH arguments. Each MATH command must end in D.

412D

This compares STACK[DSI-1] and STACK[DSI] for equality, pops both, and pushes the result.

Answered by MD XF on November 19, 2021

CGL (CGL Golfing Language)

(or Code Golf Language, this was not intentional :)

Factoid

CGL uses the stack concept like a lot of other golfing languages, but unlike them it has an infinite number of stacks that it has. Most operators operate on the current stack except some that change the current stack or move things. Stacks have numerical indexes. 0 is the default stack. The -1th stack is where input is stored.

I am unsure how bytes are counted for some of this unicode, so feel free to correct me in comments.

1 byte

h

Outputs Hello, World!. Actually pushes Hello, World! to the current stack (default 0) and the first element in the current stack is outputted by default.

2 bytes

There are a lot of possible 2 byte programs, but I wanted to show a cool operator in this one: -. - decrements the current stack, in this case switching from 0 (default) to -1 (where input is stored). ² squares the current stack. The first item in the current stack is outputted by default, so this squares the input and returns it.

3 bytes (uses a combining character)

'҄҄낄䀀

This shows off the neat string compressing function. Normally, you wrap a string in "s and it is pushed to the current stack. 's enable you to use compressed strings. ҄낄䀀 is the compressed version of Hi! (note in this example, there is no compression savings, but with longer strings there often is. Also, you can use & to compress the current stack.) Quotes are auto-completed if you leave them off.

4 bytes

-#2➕

Adds 2 to the input. adds the second stack item to the first or 1 to the first if the second stack item is non-existent.

5 bytes

-#1+Ⓧ

The # pushes the following number to the stack. Note that technically numbers are wrapped in #s, but if you leave them off they will be added between the last digit and any non-number character. The (diffrent from +) adds the first 2 stack items and pushes that to the stack. outputs the last item from the stack and exits. This therefore adds 1 to the input.

Answered by user58826 on November 19, 2021

NO!

Factoid

The only valid characters in NO! are NOno!?. This language was created 2 hours ago and I'm currently writing this with my 12th cup of coffee in my hand. This language is close to the antithesis of code golf as demonstrated by this answer to the Hello, World! challenge.

Snippets

Hello, World!

NOOOOOOOOO?Noooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooo Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Nooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Noooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo Nooooooooooooooooooooooooooooooooo
NOOOOOOOO?no

Add two numbers

NO?NOOOOOOOOOOO!NOOOOOOOOOOO
NOOOOOOOO?no

Prime Tester

NOOOOOOO?NOOOOOOOOOOO
NOOOOOOOO?no

Answered by caird coinheringaahing on November 19, 2021

tinylisp

Factoid:

tinylisp is a language made by @DLosc for an "interpret this language" challenge. Its intent is to demonstrate what a Lisp-like language can do using only very few builtins.

Here is an interpreter.

Snippet 1:

d

This single character is perhaps the most used builtin in tinylisp: the def builtin. It can be used to define variables and functions, and is basically required for every tinylisp program. Like any other lisp-like language, you define things like this:

(d x 10) // Creates a new variable x, and sets it to 10
(d succ  // Successor function, will be properly covered later
  (q (
    (x)
    (s 1 (s 0 x)))))

Snippet 2:

()

Everything in tinylisp (and basically most Lisp-like languages) are built off of parentheses. In tinylisp, these parentheses define an empty list - which is one of three data types in tinylisp:

  • Symbols
  • Numbers (which will be covered in the next snippet)
  • Lists

Snippet 3:

1.5

tinylisp has numbers, but surprisingly enough, this is not a number. Numbers (at least, numbers you can type down before compilation) in tinylisp only have the characters 0-9 in them, and anything else is a name, so these "numbers" aren't numbers in tinylisp:

-13    (contains -)
.335   (contains .)
17,232 (contains ,)

There's currently no way to define floats in tinylisp, however I'm working on implementing a fraction "class" thing in tinylisp. - Qwerp-Derp


Snippet 4:

disp

This is a four-character builtin in tinylisp, however most builtins are only one character (see snippet 1 for an example). This basically returns a value to STDOUT, with a trailing newline.


Snippet 5:

(v 1)

Yes, finally, a full statement that actually evaluates to something!

This evaluates the number 1, and therefore returns 1. That's simple enough - more complicated examples are to come.

Try it online! (from snippet 5 onwards, you should be able to test all of the programs).


Snippet 6:

(q(1))

This snippet quotes the list (1), and therefore evaluates to (1). I'm doing the best I can with 6 bytes...

q basically takes anything, and then returns the same thing, unevaluated. So for a program like this:

(q (s 1 2))

Instead of returning 3, it returns (s 1 2) instead.

Try it online!


Snippet 7:

(s 1 2)

s is the subtraction builtin; more specifically, it subtracts two integers. The above returns -1. Incidentally, s is the only way to get negative numbers in tinylisp (compare snippet 3).

Try it online!


Snippet 8:

(q(()1))

This is the simplest example of a lambda in tinylisp, and is essential to both evaluating other things and creating functions. The structure of lambdas is like so:

(q (  ;; Lambdas have to be quoted using "q", so not to get evaluated
  ()  ;; A list of arguments, in this example there are 0 args, so
      ;; this is an empty list
  1   ;; The "body" of the lambda: in this case, we're returning 1
      ;; for every input.
))

This statement is essentially similar to the Python lambda lambda:1 (which is also 8 bytes long, coincidentally). It can be used like so:

( (q(()1)) )  ;; evaluates to 1

Try it online!

Answered by clismique on November 19, 2021

Processing

Factoid:

Processing is kind of like the nicer brother/cousin of Java with its syntactic sugar, which introduces a lot of golfing opportunities, as well as GUI stuff which is built-in (because Processing is made for designers to get into programming). See the snippets for its golfing power (especially for graphics stuff).

18 bytes:

size(400,400,P3D);

This snippet not only sets the dimensions of the window to 400x400, but also enables 3D rendering (in just 18 bytes!).

7 bytes:

println

Yup, it's just println, not System.out.println. It's as simple as that.

3 bytes:

str

There's a builtin for converting to Strings from other types (e.g. int, float, long, etc.) in Processing!

Answered by clismique on November 19, 2021

Pushy

Info:

Pushy was never meant to be a language. It was originally just a postfix expression calculator, implemented with a stack. However, I (FlipTack) expanded it, adding several built-ins, loops, and (sort of) strings, it evolved into a language.

Snippets:

Note: in the showcase update, all answers are CW, so feel free to contribute to this post! Also, snippet length is no longer restricted by vote count.

Click on the header of any snippet to run it in the online interpreter!


Length 7 Snippet:

95&34_"

This program is the beginning in a chain of programs which output larger versions of themselves.

This program pushes 95, copies (&) it, then pushes 34. _ prints the stack's values, and " prints it again but as a string, resulting in:

95 95 34
__"

Which in turn outputs:

95 95 34
95 95 34
__"

5 or so iterations later, it looks like this:

95 95 34 95 95 34 95 95 34 95 95 34
95 95 34 95 95 34 95 95 34 95 95 34
__"__"__"__"
95 95 34 95 95 34 95 95 34 95 95 34
95 95 34 95 95 34 95 95 34 95 95 34
__"__"__"__"

...and it keeps growing forever. (If you iterate ~8 times, TIO begins to cut the output)


Length 3 Snippet:

:H"

This is in fact an adaption of my asterisk triangle answer. Given an integer, for example n = 5, it prints a "d-triangle" of this size:

d
dd
ddd
dddd
ddddd

This is a concise example of both loops and char-code conversion in Pushy:

:     Input times do (consuming input):
 H      Push 100 to the stack (character code for 'd')
  "     Print the whole stack, as a string.

As each iteration pushes a new 'd', this creates a triangle.

Notice there is no "end-loop" delimiter: this is normally signified with a ;. However, the interpreter automatically assumes these to be at the end of the program if omitted.


Answered by FlipTack on November 19, 2021

FurryScript

Factoid

FurryScript was made for random text generation. It has some unusual features, such as:

  • No negative integer literals
  • Subtraction, but no addition
  • The return value of a subroutine is "OK", "bad", or "very bad"

Test snippets here.

Length 1

1

An integer literal. This won't really output anything, because first you have to convert it to a string. This can be done by appending an empty string:

1 +<>

Length 2

SU

Subtraction. Pops two values y and x and pushes x subtracted from y. For example, this:

6 5 SU +<>

outputs this:

1

Answered by acrolith on November 19, 2021

Oasis

Factoid

Oasis is a language made by Adnan specialized in number sequences.

You can try it online here.

Length 1

n

Not very interesting, just push n (The current argument) and print it because implicit output.

Length 2

n1

Same as the previous snippet, but give 1 for the argument 0.

Oasis programs can have a list of hardcoded definitions for special cases.

So n1 can be described in pseudocode as:

A(n) = n
A(0) = 1

Special cases and indexes are reversed, so to make

A(0) = 1
A(1) = 4

The correct special cases definition is 41

As @Adnan pointed it out, another interesting snippet is the fibonnaci sequence:

+T

Because T is replaced with 10, so this is expanded to

+10

Which mean

A(n) = A(n - 1) + A(n - 2)
A(0) = 0
A(1) = 1

Length 3

n*1

Finally, an useful snippet!

This calculate a factorial.

     A(n) = n * A(n - 1)
n    Push n
 *   Multiply two items on the stack
     Because there is only one item on the stack, A(n-1) is pushed
  1  A(0) = 1

Length 4

n*x1

Showcase the command x (Double a number).

This is basically a factorial, but double the number returned by n*A(n-1).

A(n) = n * A(n - 1) * 2
A(0) = 1

Length 5

Tnm>1

Calculate A000533

       A(n) = 10^n + 1
T      Push 10
 n     Push n
  m    Power
   >   Increment
    1  A(0) = 1

Length 6

Tnm<9÷

A002275 aka repunits

        A(n) = (10^n - 1) / 9
T       Push 10
 n      Push n
  m     Power
   <    Decrement
    9   Push 9
     ÷  Floor divide

Answered by TuxCrafting on November 19, 2021

Alphafuck

I'll use upvote * 2 because this language uses pairs

Length 6 snippet

noT INF

This is a infinite loop. Transpiles to -[].

Length 4 snippet

uMhM

Reads a letter and prints it. Transpiles to ,..
This does the same thing: uM hM.

Length 2 snippet

um

Now we're getting into things. This snippet transpiles into Branfuck +, which increments the current memory cell by one.

Length 1 snippet

1

Anything that isn't an letter is ignored. This snippet is basically a comment.

Factoid

Alphafuck is an esolang I made that transpiles to Brainfuck.

Answered by betseg on November 19, 2021

Hexagony

Images created with Timwi's tools with link provided in the Factoid! The headers Length n Snippet are Try It Online! links :)

Length 5 Snippet - One of the Logic Gates

?<!@<

This is the AND gate, from one of the 16 Logic Gates answer by Martin Ender♦. In his answer, the explanation was left for readers as practise. Well, maybe it's time for the solution:

and1

First ? reads the first input.

If it is 0, then the IP got reflected to NE direction at < and directly wraps "to the left" (as it is <=0) and got printed at !. Whatever it reads at ?, it wraps and stops at @.

and2

If it is 1, the IP takes the right branch for the "conditional" and hit the "inclined mirror" side of < and got reflected back and hit the "hub" side of < which sends it to W direction to read another input. It then wraps and hit the "horizontal mirror" side of < and gets itself to an implicit-if at the corner. 6 instructions made within this blue path.

The different usages of < are all demostrated in this example.

If the second input is 0, then the IP goes along the red path above, which prints a 0 and reads the "third" input and stops.

If it is a 1 instead, yay we finally got 2 1s for the AND gate! The IP goes along the green path and prints out the 1 and terminates!

Length 3 and Length 4 Snippets - Cats

These 2 are simplified (thus not a very good version) of a cat program. For a real working one, please see here.

,;~

This reads and prints and also outputs a lot of trailing mysterious symbols. What's happening?

, reads a byte and ; prints it no matter what , gets (If there is no input, , will return a -1 and ; will print it modulo 256 which is 255).

Here is a trick which is useful in creating Hexagons: Using ~ (negation) to control the direction the IP goes before it reaches an if (no matter it is an implicit one or an explicit one like < and > and some other conditionals).

If you find this hard to understand, then it's worth mentioning that this is not a linear loop. As an exercise imagine the above are put into a 2-hexagon and you'll see why we need ~ to do make a loop with the implicit if :P The code basically runs in the same manner as in the length 2 snippet below!

Thus, when there is a byte, the memory will be positive and ~ makes it negative so it goes back to the top to read another byte. Yet it won't stop...

So let's see the length 4 version of the cat.

<,@;

When you try this, it looks good. Finally we have one program which stops!

cat4

It starts on the top left with an initial value of 0. A trick here which is (again) quite common - deflect the initial IP with <. This is particularly useful when the main loop should end when the calculated value is <=0.

Here it comes to the blue path. ; prints the null byte (as it is initially 0) and , reads a byte. An implicit-if decides if it should go to the green one (doing nothing and wraps back to the main blue loop for printing this byte) or it should go to the red terminal @.

In some code golf challenges, it is acceptable to have null bytes printed before the desired output. However this is not the case for the simple cat challenge attached above :P Also, this does not handle null bytes well. If you are curious how to do the cat with 6 bytes which handles and prints nothing else and stops, check it out! (The 6 bytes solution is shown after the 7 bytes)

Length 2 Snippet

This won't end. Print all non-negative integers separated by -.

!(

Not really. Indeed this is printing the unintialized edge as number (0), then decrement it and print again without a separator (-1, -2, ...)

This is an illustration of both the Implicit Loop (wrapping) and Implicit If.

The IP starts at !, goes to the right to ( and wraps to... not (directly to) ! but somewhere else first. Because the code is used to fill in the smallest possible hexagon that can hold it:

showcase_2

(Blue) For the existing code, after IP runs ( (decrements) and the memory edge becomes -1, it wraps to the middle row and goes all its way to the corner.

And, as its value is <=0, it goes to the left, which is the top row and we hit ! again which prints -1 and so on...

(Red) And if you change the source code to !), it won't print 01234.... Because when it hits the corner, the memory edge is >0 and it turns to the right option (Pun not intended) which is the lower edge, and the lower edge wraps back to the middle - however all the ops are no-ops so the IP can never escape from the loop.

Length 1 Snippet

:

If you try it, it ends soon and nothing will happen. Well 1 byte snippet in Hexagony can't do much.

: is the division in Hexagony and the result is rounded towards -infty.

Why introduce this? Lemme introduce the Memory Model of this one. Without loss of generality (it sounds good using Maths phrases), this is the initial Memory Pointer:

memory_model

Like Instruction Pointers which has an Op which it's currently on (a position) and a direction, the MP also has an edge (which holds a value) and a direction.

The edge on its left is its Left Neighbor (L) and that on right is the Right Neighbor (R).

Like +, -, *, and % (Modulo), : is also calculating L (operation) R.

One "interesting" thing about : and % is that when the Right Neighbor is 0 (the default value of an uninitialized edge), it silently errors out and hence terminating the program. This behaviour sometimes saves bytes when the termination @ is not used to stop the program.


I have read the answer here which is nice :P I also found some interesting snippets on this site thus I would like to try to get a chance to post them. I love Hexagons!

Factoid

Hexagony, as its name suggests, gives programmers a painful experience (agony) playing with Hexagons, with its Instruction Pointers (IP) and Memory Pointers (MP). Great thanks to Timwi who created Esoteric IDE for debugging Esoteric Languages and Hexagony Colorer which helps explaining the coupled IP paths.

When an IP goes out of the Hexagon, it wraps (Yup, implicitly looping) as if the Hexagon is used for tiling the ground. (Not exactly the case, because if you really wanna connect all wrapping paths, you would end up their edge overlapped like the graph on the right) Wrapping c1234 wraps to 567890 wraps back to c1234... abcd wraps to efgh and goes on... and we hit a corner.

For corner cases, there will be an Implicit-If, with <=0 is left and >0 is right. Say you (the instruction pointer when you are programming) go all the way efgh.3. to the corner. You are facing East. You would either wrap to the top which is on your left and the bottom which is on your right. If the MP is pointing to a memory edge which is <=0 you goes to the top, otherwise you goes to the bottom.

True beauty lies in making use of the implicit features and fitting different parts of the algorithm into Great Hexagonal Unity, with the use of mirrors (always like playing with scientific puzzle solving game).

Answered by Sunny Pun on November 19, 2021

Octopen-Baru

Please note, this is a noncompeting answer because this langauge came out a few minutes ago.

Length 1 Code

Simple Quine, the Ruby output is puts('見').

Length 2 Code

倍五

Which returns 100 .chr (which is 'd').

Length 3

5那}

Which returns 5.times {}, so essentially do nothing five times!

Length 4

口同愛r

Which returns r=gets;puts r, so it takes whatever you input and gives it back!

Factoid!

This language has no purposeful use of the newline character. Also, all the commands come from Kanji/中文. Also still under active development.

Answered by XiKuuKy on November 19, 2021

D2

Factoid

D2 is a Brainfuck-like turing tarpit with a 2D memory model

Length 1

.

This prints 0. Why?

. is, like in Brainfuck, the print command. But since cells are limited to 36 values, D2 use a shift-state system to print most ASCII characters. In shift state 0, the alphabet is 0123456789abcdefghijklmnopqrstuvwxyz, and since the cell is initialized to 0, this print 0.

Length 2

;.

Now this print !.

The ; instruction increment the shift state. In shift state 1, the alphabet is !@#$%^&*()ABCDEFGHIJKLMNOPQRSTUVWXYZ, so this print ! because the current cell is 0.

Length 3

>}+

Explanation:

>   Turn the cursor 90° to the right
 }  Advance in the tape
  + Increment the pointed cell

So the memory after this is:

0
1

This demonstrate D2's 2D tape

Length 4

+$}^

This set the first cell of the tape to 1, put the value in the register, advance one cell and put the value of the register in the cell.

Answered by TuxCrafting on November 19, 2021

Brain-Flak

Factoid:

In Brain-Flak a one is shorter than zero and multiplying by seven takes more characters than multiplying by eight.

Since Brain-Flak programs must have an even number of characters I have added some programs with extra spaces for the odd length snippets. These are not well golfed intentionally but rather put there in an attempt to give you a little more for your kind upvotes.

Length 2 snippet

<>

It switches to the offstack. As a single program this will always output nothing regardless of the inputs.

Length 3 snippet

{ }

This is the {} nilad it pops top item on the stack and returns its value. As a full program it just removes the last item input.

Length 4 snippet

(())

This program pushes one to the top of the stack. This is the shortest way to express 1 in Brain-Flak.

Length 5 snippet

([ ])

This program pushes the stack height to the top of the stack. At the start of a program it acts like argc.

Length 6 snippet

({}{})

This program adds two numbers.

It pops the top two elements and pushes the sum.

Length 7 snippet

This one requires a -d flag to run so +3 bytes

(This one also doesn't work on try it online)

@ij 

This is the injection flag! (With a space after it because it needs to be length 7)

This halts the program takes a Brain-Flak program from STDIN and runs it as part of the code. Its my favorite flag and (arguably) Brain-Flak's shortest self interpreter. @ij flags can be nested

Length 8 snippet

({}<>)<>

This snippet moves the top of the current stack to the other stack. It is a useful component of many programs. It starts by opening a push with ( pops the first value with {}, moves to the other stack using <> and puts the popped value down using ). When that is done it moves back to the original stack with a <>.

Length 9 snippet

({}[()]) 

(One space after the program makes it 9 characters)

This snippet decrements the top of the stack by one. It works by popping the top of the stack with {} and adding it to the negative of () (-1) and then pushing the result back on the stack.

Length 10 snippet

{({}<>)<>}

This snippet will move values from one stack to another until it encounters a zero. In many programs where it is known that the stack does not contain a zero this is used as a cheap stack reverse.

Length 12 snippet

({}<({}())>)

We've finally gotten long enough snippets that we can show off the usefulness of the <...> monad. This program increments the number underneath the top of the stack, while leaving the TOS intact. This approach can be extended. For example, this will increment the number second from the top of the stack:

({}<({}<({}())>)>)

In general, you can do:

'({}<' * n + <code> + '>)' * n

to run <code> on the number that's n from the top without affecting the rest of the stack.

Answered by Grain Ghost on November 19, 2021

Pip

An imperative golfing language with infix operators, with commands in printable ASCII. While these design decisions mean that Pip will probably never beat Jelly in a golf contest, they also make the language much easier to learn and use.

Factoid

To my knowledge, Pip was the first golfing language to have built-in regex support.

The header of each snippet is a TryItOnline link.

Length 1

a

Pip's default method of getting input is by command-line arguments (hereinafter "cmdline args"). The first five args are assigned to the variables a through e, and the whole list is assigned to g.

Since it is at the end of the program, the expression a is auto-printed. So this program outputs the first cmdline arg.

Length 2

/q

To get input from stdin, use the q special variable. Every time it is referenced, it reads a line of input.

Many operators have both binary and unary versions. This is expected behavior for operators like -, and makes good sense for others like ^ split and J join. Here we have a somewhat unusual example: unary / inverts its argument. Inputting 4 will give 0.25 as output, and vice versa.

This snippet also demonstrates a feature that Pip shares with Perl and PHP: numbers are strings and strings are numbers. Both are represented by a data type called Scalar. Upshot: you don't have to convert q's line of input to a number before doing math with it.

But what happens if you input something that's not a number, like Hello world? In a numeric context, it's treated as 0. Dividing by 0, like most error conditions, returns the special nil value, which produces no output when printed. If you want to see what went wrong, you can use the -w flag to enable warnings, in which case Pip will tell you:

Inverting zero

Length 3

Uses the -p flag (+1 byte).

^g

As mentioned above, g is a list of all cmdline args. Many operators work itemwise on lists, and ^ (split) is one of them. This code splits the items of g into lists of characters.

If you ran this 2-byte code without the flag, it wouldn't be obvious what the program did, because Pip's default way of outputting lists is to concatenate the items together. To demonstrate that the split operation worked, we need to change the output format. About half of Pip's command-line flags have to do with list formatting. The -p flag applies RP (analogous to Python's repr) to the list before outputting it, making it easy to see the structure:

> python pip.py -pe "^g" 42 Hello
[[4;2];["H";"e";"l";"l";"o"]]

Use the TIO link above to play around with the other list flags (-s, -n, -l, -P, -S) and see how the output changes.

Length 4

z@<h

Lowercase letters h through z are global variables, preinitialized to different values. z is the lowercase alphabet; h is 100.

The @< "left-of" operator returns a slice from the left end of an iterable (scalar, list, or range). It's equivalent to Python iterable[:index]--except that the Pip version works even when the index is greater than the length of the iterable. In that case it repeats the iterable until it's longer than the index, then takes the slice (like take + cycle in Haskell). So z@<h gives the first 100 characters of the lowercase alphabet:

abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuv

Length 5

2>1>0

Comparison operators chain, as in Python. This program returns 1 (true).

Answered by DLosc on November 19, 2021

Dotsplit

(whoops I forgot the link before :p)

(pair of) Factoid(s):

Dotsplit is a mostly syntax free language, with odd builtins (kind of like mathematica), but is currently in it's infancy. Dotsplit is named after the tokeniser used in the interpreter: str.split(). This is a weak tokeniser, but it fulfills all needs of the language, so far anyway.

1 byte:

D

D does

...

nothing. it isn't a tiny builtin, unless you count a nop as a builtin, and it's only a nop because it isn't a defined command. Dotsplit has relatively long command names for most things. Note that the shortest happens to be three long. anything that isn't a defined command is ignored. also note commands are case insensitive, so if it were a command, d would be the same as D

2 bytes:

still not much interesting

 b

b with a leading space. This program functions identically to b, as well as D, because nops, but if b was a command, b and D would not be the same, but b and [space]b would. Spaces are used to separate commands, but otherwise are ignored. Next upvote, and we get an actual command!

3 bytes

First command!

aDd

This will pop a and b, and push a+b. Popping from an empty stack yields 0. hence, this program will leave one 0 on the stack. add is case insensitive, and will function regardless of case (AdD will also work)

4 bytes

There are a fair amount more commands with 4 bytes, not many still. I chose this one

derp

This program will wait for input by the user. If input is "derp" (case-sensitive), it prints "Derp". Otherwise, "Nope"

Answered by Destructible Lemon on November 19, 2021

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.

Answered by ASCII-only on November 19, 2021

FEU

FEU (File Edition Utility) is a heavily regex-based language to edit files.

0 bytes

Cat program. Yep.

In FEU, the input is took implicitely at the start of the program anv every command works on the input. The input is printed at the end.

1 byte

/

/ execute the next block each time the input match a regex. Here, it will crash anyway because the block is not closed (end).

2 bytes

u/

The command u convert the input to unary, and the input is implicitely printed.

3 bytes

s/a

s is the substitution command, so this remove the first a in the input.

Empty fields are optional.

Answered by TuxCrafting on November 19, 2021

Logy

Logy is a logic, imperative and functional programming language.

0 bytes

A program without the main rule do nothing.

1 byte

#

Start a line comment

2 bytes

->

The rule definition operator

Answered by TuxCrafting on November 19, 2021

hansl

hansl is a programming language that is used in the statistical software project gretl since 2001. It resembles a mixture of R, Stata, and C. It operates with datasets, time series, vectors, matrices, and functions. Just as in R, there are dozens of user-written packages for econometrics and data analysis. It is a matrix-oriented interpreted language that is Turing-complete (!). Its fortes are econometric estimation and numerical maximisation, and it can be integrated with R, Ox, Octave, Stata, Python, Julia, and gnuplot.

Length 1 snippet

~

You know how difficult it can be to build matrices from vectors? One can attain the effect by reading the input row-wise, column-wise, or through assembling the mess into a dataset? In hansl, you do not hassle: just write ~ between the two vectors, and voila, you get them bound in tight leather together vertically: A~B. Do you have two matrices you want to assemble? X~Y, easy as pie.

Length 2 snippet

$h

This neat accessor returns the series of estimated conditional heteroskedasticity from the last GARCH model. Doesn’t it amaze you that esoteric programming languages have abbreviations for everything? Take that, MATL!

Length 3 snippet

ols

This is probably the most frequently used estimation method in all of econometrics. This command estimates a linear regression model describing the relationship between the dependent variable and predictors (like ols wage 0 age education married), returns the full model and generates many useful accessors (like $uhat for residuals, $aic for Akaike information criterion etc.)

Factoid: Its name comes from the famous fairy tale “Hansel and Gretel” by the Grimm brothers, with a modern twist (like Flick-r, Tumbl-r, and similar names, but gret-l omitted the penultimate vowel long before it became mainstream!).

Answered by Andreï Kostyrka on November 19, 2021

Copy

Copy is my new esolang. The only branching operations are skipping a instruction and code removing and copying, and the only arithmetic operations addition and negation.

Length 6

skip 0

skip skip the next instruction if its argument is not 0. So here, it's essentially a no-op.

Length 7

add a 5

Add 5 to the variable a. Since a is undefined, it set it to 5.

Length 8

add a -8

Add -8 to the variable a. This is to demonstrate than signed numbers are allowed as command arguments.

Answered by TuxCrafting on November 19, 2021

MiniStringFuck

MSF- is a way to compress the unique characters of any 0-255 ASCII string to just two characters; and it does pretty well! Although code might just be long.

Length 1 snippet

.

Outputs 0x00.

Length 2 snippet

+.

Outputs 0x01. This does not only demonstrate the . (output), but also the + (accumulator). + essentially changes the accumulator's value (acc) to (acc + 1) % 256.

Length 3 snippet

,+.

It does not really output the next character; it's the same as above, because non-+. characters are ignored.

Length 4 snippet

+.+.

Yay multiple chars!! This outputs 12 (escaped chars).

Length 5 snippet

+.+..

This prints 122. Yes, we need too much upvotes yet to get to a reasonable program.

Length 6 snippet

+.+.+.

Prints 123. Finally something that looks a little bit more interesting than just some random sequence of unprintables.

Answered by Erik the Outgolfer on November 19, 2021

///

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

Answered by acrolith on November 19, 2021

SX

Length 1 Code

Compiles to: pass

Length 3 Code

10才

returns 11. 才 is equivelant to C's ++.

Length 4 Code

品*30

returns the circumference of a circle with a diameter. Assuming math was importing.

Length 5 Code

送我(@)

compiles to def __init__(self):print(self) and will work if put inside a class.

Factoid: sorry pass isn't really that interesting. Sorta interesting, SX is one of the first golfing langauges (I made it when I was in 7th or 8th grade. It also compiles to python.

Answered by XiKuuKy on November 19, 2021

Logicode

Factoid:

Logicode has a very limited amount of built-ins (7 built-ins, of which 6 are single-char), which makes it pretty difficult to program anything meaningful in.

Also, it's built on logic gates, as the name suggests, and that's it - which makes it doubly hard to code stuff in.

You can try it online here.

Length 1 Snippet:

+

The + is not addition, as that can be achieved easily. It's concatenation between two "numbers" (which are binary): So, something like 11+1 is not 100, as with regular binary addition, but 111.

Length 2 Snippet:

->

-> is used in two main things: circuits (which are Logicode's version of functions) and conditionals (if statements). It is used to separate the executed code from the arguments (in the case of circuits) or the condition (in the case of conditionals).

Length 3 Snippet:

out

This is a declarer, kinda like var in Javascript to declare a new variable. Logicode has a declarer for anything: out for output, var for variables, circ for circuits (which are basically functions in Logicode), cond for conditionals.

Length 4 Snippet:

!100

The ! is a logical NOT, which is operated on every digit of the binary string that follows. In this case, the snippet evaluates to 011.

Length 5 Snippet:

1&1&1

In Logicode, you're allowed to stack multiple two-arg (dyadic) operators together, as seen here. The & is a logical AND, and the snippet evaluates to 1.

Length 6 Snippet:

@11011

Yay, ASCII support! Because the default "type" of Logicode is binary strings, the @ converts binary to ASCII codes (mod 256). In this case, the character generated is ESC (ASCII character code 27).

Length 7 Snippet:

1000<<<

This program takes the tail of 1000 three times. A tail is essentially every character but the first, so repeating this three times gives us:

1000 -> 000 -> 00 -> 0

So this evaluates to 0.

Answered by clismique on November 19, 2021

Straw

Straw is a 1D stack-based language I created.
It mainly operate on strings.
You can try it online here.

Length 1

<

Take one line of input and exit.

Length 2

->

- take an item from the secondary stack, and > print it.
Straw have 2 stacks: The first is initialized with an empty string, and the second with Hello, World!.
So this code prints Hello, World!.

Length 3

9#>

Any character which is not a command is pushed on the stack, and # convert a decimal number to unary. It's needed to make any operations on numbers, because Straw don't have numbers, it only operate on strings. So this example prints 000000000.

Length 4

<<+>

Take two lines of input, concatenate (+) and print.

Answered by TuxCrafting on November 19, 2021

Brachylog

Factoid

Brachylog is a declarative logic programming language based on Prolog. Its name is constituted of the prefix brachy- (meaning short, from ancient greek βραχύς) and the suffix -log, to mark its link to Prolog.

Length 1

r

A seemingly simple program, that is useful to understand some fundamental basics about Brachylog (and declarative programming in general): Reverse something.

In Brachylog, the program r is a main predicate consisting of one rule (namely, r). All rules in Brachylog implicitely start with the Input (noted ?) and end with the Output (noted .).

Therefore, our program is really ?r., which can be read as Output is the reverse of the Input. The built-in r - Reverse works on the three main data types of Brachylog: lists, strings and integers.

But more interestingly, it is a relationship that we state with r, not a one-way function like most programming languages. As such, r also works as expected when the Output is ground and the Input is not! It even works if both the input and the output have no value, though that doesn't show well on the online interpreter and with a program limited to one character.

We will continues to see in the next examples that predicates in Brachylog are relationships between variables and are as such much more expressive than traditional imperative function. We can also note that the Input and Output of predicates are merely called that because that's usually how those variables are used, but those are simply names and they don't mean that for example the Input necessarily has to be a ground variable.

Length 2

r?

Now that we know that r is reverse, and that ? is the Input, you can probably guess what this program does: test whether the input is a palindrome or not.

Indeed, r? is really ?r?., which can be read as: Input is the reverse of the Input, and Output is the same as the Input. Since we do not need the Output at all here, the second part of the sentence can be disregarded and we then see that it is indeed a palindromeness checking program.

The program .r would have worked the same if we passed our input through the Output variable.

Length 3

:^a

As you can see from the TIO link, the code above squares each element of the input. ^ being the squaring built-in predicate, and a being Apply, a meta-predicate.

In Brachylog, all predicates have only an input and an output argument. Therefore, when we need to "pass" more than one thing to the predicate, we put them in a list.

This is what we are doing with :, which is also the list separator. By writing :^, we are constructing the list [Input, brachylog_power]. So, just like numbers, strings and lists, we can also put predicates in lists.

Apply takes the last element of its input argument as being a predicate, and queries that predicate each time with an element of the rest of its input argument as input (hence why it is called a meta-predicate). The output of apply accumulates the outputs of the queries. This predicate is usually called map in other languages (maplist in Prolog).

Length 4

:@[f

Continuing on meta-predicates, here is f: Findall. As its name suggests, this will find all valid outputs of a predicate for a specific input.

Here, the input to Findall is the list [Input, brachylog_string_prefix]. The predicate string_prefix @[ is true if its output is a prefix of the input. By running Findall on it, we will obtain all prefixes of ?.

Note that the string in string_prefix only comes from the fact that it is a 2 symbols predicate which starts with @ (which represent operations that are more often done on strings). This predicate of course doesn't only work on strings, but also on integers and lists.

Length 5

:Lc.r

This is probably my favorite Brachylog program (most likely because it is twice as short as the Jelly answer on this challenge!). This is a program which palindromizes its input.

In Brachylog, strings and integers can contain variable characters/digits, just like how lists can contain variables as elements. Therefore, :Lc. means “Output is the result of concatenating the Input and a variable L. Then, we impose with .r that the output reversed is still the output (thus, that the output is a palindrome). This will force Brachylog to unify the variable values of L so that the output is indeed a palindrome.

Length 6

:1f
~c

Here is another example of the use of f - Findall and c - Concatenate.

The first line is the main predicate and states “Find all valid outputs of predicate 1 given the Input as input”. The second line is predicate 1 and states The output, when concatenated, results in the Input.

Here, ~ is a simple control symbol which "flips" the arguments of the following predicate: AcZ means “Z is the result of concatenating the elements of A” whereas A~cZ means “concatenating the elements of Z results in A”.

Therefore the program above will find all possible lists of strings (excluding the ones containing the empty string), which when concatenated will result in the input.

Note that ~c is not a second built-in which does the reverse of c ; it is the same as c, but called with swapped arguments. To convince you of this, rewriting predicate 1 as ,.c?, will result in the same program.

Side note: this program could have been written :{~c}f, which does the exact same thing. Choosing one or the other is mostly a matter of preference.

Length 7

:1y
#p=

This demonstrates another meta-predicate: y - Yield, and a major feature of Brachylog: constraints-based arithmetic.

y - Yield is a meta predicate very similar to f - Findall, the difference between the two being that y will unify its output with the first N outputs of the queried predicate (N being the penultimate element of the input arguments), instead of all of the outputs. This is thus very useful for predicates that have an infinite number of choice points, such as arithmetic series.

In Brachylog, all integer arithmetic is based on constraints. This makes operations on integers very declarative in nature ; if we declare the relationship that X + Y = Z (which in Brachylog would be written as X:Y+Z), then this constraint will hold even if those variables have no ground value. Adding more and more constraints will keep on reducing the search space for the possible values of those variables. Then, the labeling process (using = in Brachylog) will assign values to variables such that they respect all constraints that were applied to them.

#p - constraint_prime is a predicate which constrains its input ? (which is unified with its output .) such that it must be a prime number. Using = - Equals, we can then label that variable so that it takes a ground value. The labeling process will order choice points according to the magnitude of the values, which is why overall this program yields the first N prime numbers, starting from 2.

Length 8

~l<:#pa=

As you can see, this does exactly the same thing as the previous 7 bytes program. This one though is much more easier to describe and understand.

We use ~l to get a list whose length is the Input. We then impose with < that the list must contain integers and must be strictly increasing. Using Apply, :#pa then constrains each integer of the list to be a prime number. We then use = to label the values of that list, which results in a strictly increasing list of prime numbers.

Length 9

#0|@e+:0&

This program computes the digital root of its input.

Just like in Prolog, we can write multiple rules for a single predicate, using |: the first rule #0 constrains the Input = the Ouput to be a single digit. If this is not possible, the second rule @e+:0& will split the input as a list of digits, then sum them and call Predicate 0 (the main predicate) recursively.

Answered by Fatalize on November 19, 2021

Cubix

Click on any snippet's header to try it in the online interpreter!

For reference, the text in bold tells you the important stuff.

Factoid

Cubix is a stack-based language, created by me, which runs like a 2D language such as Befunge. The main difference? The code is run on the outside of a cube.

Length 1

@

This is pretty much the character most commonly used. Why? Because it immediately ends execution of the program. In fact, it's the only way to end the program.

This is useless as a program, though, because it gets turned into this cube:

   @
>. . . .
   .

Where the IP (instruction pointer) is started at the arrow, and . is a no-op. This just loops around forever. Take a good look and you'll see why every possible 1-byte program never ends (or does anything at all).

Length 2

.O

Now that we've gotten over the length-1 barrier, we can finally see some output! Here's the cube net:

   .
>O . . .
   .

where the IP starts at the arrow. O takes the TOS (top-of-stack) and outputs it as a number. If the stack is empty (e.g. at the beginning of the program), this prints 0.

When the IP gets over to the right edge of the above cube-net, it wraps back around to the left edge, onto the O again. Thus, this program prints 0 forever.

Length 3

@O/

Our first cheerleader program that terminates! This gets mapped to the following net:

   @
>O / . .
   .

where the IP starts at the arrow. As we've seen before, the O prints the TOS, which is currently 0, as a number. Next comes a new character: /. This is a mirror. There are five different mirrors: /, , |, _, and T. Mirrors reflect the IP from one direction to another.

When the IP hits this mirror, it is redirected to the north. This puts it on the top face, which is @. Thus, the program is terminated, and the output is 0.

Length 4

@Io^

This expands into the following cube net:

   @
>I o ^ .
   .

A bunch of new characters here:

  • The first character is I, which inputs an integer from STDIN.
  • Next comes o. This is like O, but outputs a char-code instead of an integer.
  • After that, we see ^. This is one of four arrows: ^, >, v, and <. Arrows point the IP in a specific direction. ^ points the IP north, where it hits the @ and terminates.

Length 5

@i?o_

Finally a (somewhat) useful program. This expands into the following cube net:

   @
>i ? o _
   .

This is a cat program: it prints the entirety of the input, one char at a time.

The first character is i, which inputs a char-code from STDIN. If there's nothing in STDIN, it pushes -1.

Next comes ?. This is one of the most useful chars: it redirects the IP based on the sign of the TOS. If the TOS is negative, the IP turns left; if the TOS is positive, the IP turns right; if the TOS is zero, the IP continues in the same direction.

The combination of these chars does the following:

  • If the input is a null byte, the IP continues straight, outputting with o and wrapping back around to the i. (The _ is a mirror which does nothing when the IP is traveling east-west.)
  • If the input is anything else, the IP turns right, wrapping around to the bottom and hitting the _. This turns it around; it goes back across the bottom and hits the ? again, turning right. This time, though, it's sent through the o and back around to the i.
  • If there is no more input, the IP turns left, hits @, and ends the program.

Length 6

9O/;)o

Our first happy program! ;) This expands into the following cube net:

   9
>O / ; )
   o

The first character is O, which prints the TOS (currently 0). Then the IP hits a mirror / which redirects it over the top face onto the 9. Digits push themselves to the stack. Note that they do not concatenate; 12 pushes a 1 and a 2.

So now the TOS is 9. The IP comes down on the other side of the cube and hits the ), which increments the TOS by 1. Now the TOS is 10, which tells the o on the bottom face to output a newline.

The IP comes up and hits the mirror again, turning to the east. The next character it hits is the ;, which pops the TOS (removes it). The stack is now back to its natural state with infinite 0s.

Next is the ), which increments the TOS to 1. Now the IP is back at the start of the program, except the TOS is now 1 instead of 0. Can you figure out what this program does?


Feel free to add more interesting snippets!

Answered by ETHproductions on November 19, 2021

Woefully

Now with TIO!

Factoid:

Woefully is a 2d language with no traditional conditionals (ooh, that rhyme). The closest thing it has to conditionals is the boolean/not_zero command, which pushes int(stack_A.pop()!=0). It's also pretty weird in other ways.

It isn't really possible to even write a program in less than 7 characters, unless you count printing the "error" message as a program, or immediately halting as a program, so perhaps I'll multiply the votes by 4 to get the amount of bytes I can have, if that's allowable (context: it takes 266 bytes to write a truth machine, unless it could be golfed more,)

1*4 bytes

boom

this program technically doesn't error, but just prints "confuse :(", the "error" message of the language, which counts as regular output as it goes to STDOUT, not STDERR. This program doesn't conform to the program composition requirements (needs to have no characters that aren't pipes, spaces and newlines, needs to have at least one space, needs to have no spaces at the start and end of lines), and so automatically prints the message "confuse :("

BTW it is going to be a while before anything really interesting, like even a program that just takes input, or pushes a number, so you might want to look at my truth machine to see what Woefully looks like

2*4 bytes

| |
|| |

Ooh, we have the first program that doesn't just print "confuse :(" and die. This program does... nothing. It is in an infinite loop of nops

Why it nops forever

diagram!

v
||
|||
  X

The char pointer, the first of two pointers, starts at the character pointed to by v. The instruction pointer will find the first space after this char, and execute the path of spaces it is a part of. The shows the path. the instruction pointer goes down this path, but does nothing, since lines that are two-long are nops. Once it finishes the path, (symbolised by the X), the instruction pointer returns to the char pointer, which has not moved, and executes it again, forever.

3*4 bytes

| |
| |
| ||

This program terminates in an error (not confuse, but an actual error), but why?

three down executes the A to B command, popping the top of the A stack, and pushing it to the B stack. (there are two stacks). However, the program does not immediately fail, because the stacks start with values already on them: one zero each, it runs once normally, then fails the next iteration of the loop.

4*4 bytes

||| |
|| ||
| ||

This program pushes zero to stack A infinitely. this is because all diagonally down left commands push the length of the command, minus three. minus three because a command that is two long is a nop, so the shortest push command is three long, and the smallest push-able value is zero.

5*4 bytes

| || |
||| ||
|| |||

I didn't really have anything interesting (apart from some more erroring commands) to show this time, but I realised none of the snippets halt, though some error, so this snippet just halts, without doing anything (including the push at the right)

diagram!

v       char pointer starts pointing here
|X||a|   X has the first space after that character, so it's path is executed
|||a|| X halts the program
||a|||   a - never executed

Answered by Destructible Lemon on November 19, 2021

Racket

Factoid : A programmable programming language: Racket is a full-spectrum programming language. It goes beyond Lisp and Scheme with dialects that support objects, types, laziness, and more. (https://racket-lang.org/)

(I am surprised no one has added Racket till now).

Functions or procedures need to be in parentheses. First term in parentheses is procedure name, rest are its arguments. If an argument is a procedure, it has to be in its own brackets. Values (non-procedures) are written without brackets.

Main syntax difference between Java and Racket is f(a, b) vs (f a b), x+y+z vs (+ x y z), x == y vs (eq? x y) and x=2 vs (define x 2), or if already defined, (set! x 2). There is no need to declare types like public static void or int char string etc.

Length 1

i

Prints value of i.

Also: + - / * are functions:

(+ 1 2 3 4)  

Output: 10 (all numbers are added together)

(* 1 2 3 4)

Output: 24 (product of all numbers)

(/ 20 5 2)

Output: 2 (20 is divided by 5 as well as 2)

(- 10 5 2)

Output: 3 (5 and 2 are subtracted from 10)

Length 2

pi

Prints value of pi:

3.141592653589793

Length 3

let 

For local binding as in:

(let ( (x 5)   (y 10) )
  (println  (* x y))
)
; x and y are not visible here; 

Also:

map

Subjects each item of a list to the sent function, e.g. to double every item of the list:

(map    (lambda(x) (* 2 x))    (list 1 2 3) )

Output:

'(2 4 6)

Also:

for 

Standard for loop as well as its extensions:

for* for/list for/sum for/product for/first for/last for/and for/or 

There are more extensions https://docs.racket-lang.org/reference/for.html !

Length 4

Conditionals:

cond 

For example (from https://docs.racket-lang.org/racket-cheat/index.html):

(cond 
  [(even? x) 0] 
  [(odd? x) 1] 
  [else "impossible!"]) 

Also

list

Being derived from Lisp & Scheme, list is very important data structure here:

(list 1 "a" #a (list 1 2 3)) 

Length 5

match 

Match is like case-switch:

(match x
  [3 (displayln "x is 3")]
  [4 (displayln "x is 4")]
  [5 (displayln "x is 5")]
  [default (displayln "none of the above")])

Also:

apply 

This opens a list and provides all elements to the function, for example:

(apply + (list 1 2 3 4 5))

becomes:

(+ 1 2 3 4 5) ; => 15

Length 6

Define: a very basic function- to assign value to a variable:

(define s "A string")
(define n 10)

Also:
printf - the print function:

(printf "~a ; ~a ~n" s n)

Output:

A string ; 10 

Also: Filter - a function that filters a list for items which give true value to the specified function (sent as an argument):

> (filter string? (list "a" "b" 6))
'("a" "b")
> (filter positive? (list 1 -2 6 7 0))
'(1 6 7)

The test function can be specified:

> (filter 
    (lambda(x) (> x 2))    ; function to test each element
    '(1 2 3 4 5))          ; full input list to be filtered

Output:

'(3 4 5)                   ; output list of elements greater than 2

Length 7

println : one of most commonly used function. Prints out the sent string with a newline character at end:

(println "String to be printed")

(Note: examples are from various sources on the net).

Answered by rnso on November 19, 2021

Fourier

Factoid

I originally intended this to be a golfing version of Brainfuck... Alas, due to the simplicity of the language structure, this language is in no way good for golfing.

Snippets

Length 0 Snippet:

         

An empty program does nothing. No input, no output, no change to the accumulator.

Try it online!


Length 1 Snippet:

o

o outputs the value of the accumulator. Since the value of the accumulator is 0 at the start of the program, 0 is outputted.

Try it online!


Length 2 Snippet:

^o

^ increases the value of the accumulator by one. The o then outputs the value of the accumulator, printing the number 1.

Try it online!


Length 3 Snippet:

9ro

r generates a random number between 0 and the value pf the accumulator. Here, it generates a random number between 0 and nine and then o outputs the number.

Try it online!


Length 4 Snippet:

4^do

Uses the fifth function of the date function: outputting the current year. The other functions of the date function are:

  • 0: current second
  • 1: current minute
  • 2: current hour
  • 3: current day
  • 4: current month
  • 5: current year

Try it online!


Length 5 snippet:

I*10o

Sets the value of the accumulator the user's input, multiplies it by ten and outputs the number. It's a basic program but demonstrates how user input works.

Try it online!


Length 6 snippet:

2(5ro)

This program prints random numbers until the random number is 2. It is an example of looping:

x(code here)

Repeats the code within the brackets until the resulting value of the accumulator within the brackets is equal to the value of the accumulator at position x.

Try it online!


Length 7 snippet:

|7o|GGG

This is an example of a function. It works like so:

|code here|x

You contain the function code within the pipes and store the function in the variable x (can be any variable name). To run the code within the pipes, just write the function name.

The function here prints the number 7 twice because g (the function name) is called twice.

Try it on FourIDE!


Length 8 snippet:

I^~NN%2o

This is a simple program which takes an input of a single number and tells you if the number is even (1) or not (0).

It is an example of how Fourier uses 1 and 0 as truthy and falsey values.

Try it online!

Answered by Beta Decay on November 19, 2021

SQF

Factoid:

SQF (Status Quo Function) is the scripting language for the Real Virtuality engines (O:FP, ArmA, ArmA 2, ArmA 3). The games written for the engine are functionally just mods made in SQF.

Length 0 Snippet:

This is technically valid SQF, and does nothing unless it is treated as code, in which case it is a no-op.

Length 1 Snippet:

+

+ does the usual things in SQF:

  • Concatenation of arrays
  • Concatenation of strings
  • Addition of numbers

And something really cool as well:

  • Deep-copying of arrays (as a unary prefix)

Length 2 Snippet:

_x

_x is a magic variable which is used in these cases:

  • The current element in the optional predicate block argument of count (an array function)
  • The current element in the main block of a forEach block

Length 3 Snippet:

a-b

This subtracts b from a, if the operation is applicable to the types of a and b.
Like quite a few things in SQF, it does something particularly neat with arrays:

  • When a and b are arrays, the result of a-b is the set exclusion of b from a

Answered by Οurous on November 19, 2021

Coffeescript

Description:

Coffeescript is a language that compiles into Javascript. It's much less verbose than JS (and about the same as ES6), which makes it friendlier for ing.

Factoid:

Coffeescript doesn't require brackets with function calls.

Length 1 Snippet:

=

The = sign means a lot of things in Coffeescript - it can assign both functions and variables in one fell swoop, much like Javascript.

Length 2 Snippet:

**

This is the power sign, which is used like this: a**b. It replaces JS's Math.pow(a,b), which saves 11 bytes.

Length 3 Snippet:

(n)

This is an argument in CoffeeScript, and is used like so:

{function name} = (arg1, arg2...) ->

(This is basically the same as JS, but I just wanted to show off functions - because they're so different).

Length 4 Snippet:

0..5

For-loops are different in CoffeeScript. This snippet, when put into this context:

for a in[0..5]

Is the same as JavaScript's

for (a=0, a<5, a++)

and Python's

for a in range(5)

As you can see, this snippet shows the byte-saving powers of CS.

Length 5 Snippet:

n=->1

Yay, a full function!

This snippet creates a function, n, with no arguments, which outputs 1.

Length 6 Snippet:

if n<1

This is an if statement, in CS. Notice the lack of a colon, or curly brackets (yes, no curly brackets!). This compares n, and checks if it's less than 1.

Simple enough.

Length 7 Snippet:

class A

This is a class declaration in CoffeeScript. Despite there being no support for classes in JavaScript, there's classes in CS - and they work exactly the way you expect them to.

Answered by clismique on November 19, 2021

Arithmescript

Making an entry for Arithmescript here.

Codes

Length 1 snippet

i

Prints the value of i in the console.

Factoids

  • I am the creator of Arithmescript.
  • Arithmescript extends JavaScript.
  • It is sort of discontinued.

Demos

You can try out code in the latest version of Arithmescript at the official site.

Answered by Peanut on November 19, 2021

Maple

Length 15

type(1,posint);

Type checking is an important aspect of input handling for procedures and commands.

> type(1,posint);
  true

Length 14

plot3d(cos(x))

3D plots are very useful for visualizing mathematical surfaces. enter image description here

Length 13

Matrix(10,10)

or

<<1,2>|<3,4>>

Matrices are one of Maple's fundamental data structures. It is possible to perform many common operations, including numerous operations in Linear Algebra on matrices. There are several calling sequences for making a new Matrix. Above are two of the most common: The Matrix command generates a new Matrix with r rows and c columns:

Matrix(r,c);

The shorthand notation < > can also be used to input a matrix.

<<1,2>|<3,4>>;

2x2 Matrix

Length 12

f:=x->2*x+12

A function can represent a function call, or application of a function or procedure to arguments. In the example above, a new function called 'f' is created that takes an argument 'x', and returns 2 times the argument plus 12.

> f:=x->2*x+12;
> f(4);
  20

Length 11

assume(x>0)

The assume routine sets variable properties and makes it possible to set relationships between variables. A common use is shown in the example above: the assume routine declares that a variable 'x' is a positive real constant. Applying such an assumption makes it possible for Maple to simplify expressions such as:

simplify( sqrt( x^2 ) )

Which returns 'x' only after an assumption is placed on the variable 'x'.

Length 10

D[1](f)(x)

The D command serves different purposes. It is primarily a differentiation command, similar to one of Maple's most used commands, diff, but it is also more general in two ways: it can represent derivatives evaluated at a point and can differentiate procedures.

Length 9

exp(I*Pi)

Euler's identity states that exp(I*Pi) + 1 = 0. In Maple's 1-D code, this is 9 characters long, however using 2-D Math notation, this can be displayed using 3 characters (4 if you count the space needed for the implicit multiplication of I and Pi):Euler 2-D Math

Length 8

plot(Ci)

This is the first entry that uses one of the most important parts of Maple: plotting. Even though it is possible to construct a plot with less characters, i.e. plot(), this example gives a much more interesting result: the plot of the Cosine Integral.

Cosine Integral

This certainly isn't the last time you'll see a plot in this list as there are many more interesting expressions and plot variants in Maple. Some other interesting 8-character plots include: Sine Integral:

plot(Si)

Exponential Integral:

plot(Ei)

Natural Logarithm:

plot(ln)

Length 7

cos(Pi)

When evaluating symbolic expressions, Maple returns results in an exact symbolic form. This means that the results are not approximated to any number of digits, rather the result is the exact value for the result. This is also what is known as having results with "infinite precision"!

> cos(Pi);
  -1
> evalf[5]( cos(Pi) );
  -1.
> cos(Pi/4);
  sqrt(2)/2
> evalf[5]( cos(Pi/4) );
  .70710

Length 6

rand()

The rand command returns a random integer sampled uniformly from the range 0 to 10^12−1. Maple can also sample from numerous other statistical distributions.

> rand();
  395718860534

Length 5

1.*Pi
1.0*π

Maple supports arbitrary precision arithmetic. For example, here's Pi to 314 digits:

> evalf[314](Pi);
  3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063

Length 4

999!

Maple can work with very large integers. The Factorial operator computes factorials for given values. The number of digits of 999! is:

> length(999!);
  2565

Length 3

x$5

The $ operator can be used to create a sequence for a given expression. For example,

> x$5
  x, x, x, x, x
> i^2$(i=1..3)
  1, 4, 9

Length 2

x:

Using the colon operator suppresses output for entered commands.

Length 1

Maple is a symbolic computation engine, so you can use the infinity character in computations for integrals, limits, etc. Also, results from symbolic computations can be considered to have "infinite" precision since Maple doesn't approximate purely symbolic results (see Length 7 example).

Factoid:

Maple is a mathematical programming language and computation environment. However, the name “Maple” is not an acronym for Mathematical Programming Language, it’s a reference to its Canadian heritage.

Answered by DSkoog on November 19, 2021

Pyke

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

1 byte:

r

Try it here!

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

1: GOTO_START

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

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

2 bytes:

SB

Try it here!

The factorial function - not a builtin. Equivalent to

product(range(1, input+1))

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

3 bytes:

]UP

Try it here!

This actually shows off 3 interesting features:

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

4 bytes

F_+

Try it here!

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

rtn = []
for i in input:
    rtn.append(i+"_")
rtn = "".join(rtn)
print(rtn)

5 bytes

#.b){

Try it here!

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

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

6 bytes

C695@]

Try it here!

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

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

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

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

7 bytes

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

.dॳv

Try it here!

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

A compressor for Pyke can be found here

8 bytes

1?tY/r"Z

Try it here!

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

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

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

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

9 bytes

S#2%!)1|e

Try it here!

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

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

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

10 bytes

Cy1H30M"+t

Try it here!

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

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

11 bytes

V.X".X-+||"

Try it here!

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

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

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

0: upper (all characters have this as default)

1: topleft (corners if undefined have this)

2: left line

3: right line

4: lower line

5: topright corner

6: bottomright corner

7: bottomleft corner

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

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

12 bytes

Whoever said golfing languages had far to many useless builtins?

CB"Jupiter"@

Try it here!

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

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

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

13 bytes

~1#_P)D3M*+mP

Try it here!

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

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

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

14 bytes

y0:0"w?Vs5
​

Try it here!

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

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

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

0 - years

1 - months

2 - days

3 - hours

4 - minutes

5 - seconds

6 - weeks

7 - 4 years

8 - decades

9 - 12 hours

15 bytes

.dȇጾȞĶl5

Try it here!

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

Answered by Blue on November 19, 2021

QBIC

I'm trying to teach QuickBasic to do codegolf (and myself in the process), so I'm creating the language Quick Basic Interpreter for Codegolf, or QBIC for short.

0 byte factoid

Most of QBIC's strength lies in just making a shorthand for QBasic's expansive syntax, but I've also incorporated several features of my own. When generating the trans-compiled BAS file, a standard header is imported that implements some of these features. For instance, the numbers 1 through 10 get initialised as variables q through z. This occasionally saves me some bytes when initialising a FOR loop, and shaves a byte off of using 10.

1 byte

}

The above statement will do ... exactly nothing. When found in the QBIC code, it wil automatically add END IF's, NEXTs and LOOPs for every opened IF/FOR/DO construct it finds (in the correct order, naturally). Note that ] does the same for one language construct, where } closes all opened constructs.

However, since we've not yet opened any of those constructs, this does nothing and results in an 'empty' Qbasic BAS file. Also, at the end of compiling QBIC, the compiler will run this statement automatically.

2 bytes

?z

This will write 10 on the screen. In QBIC, the letters of the lower-case alphabet are references to numerical variables. This is retained from QBasic, where PRINT a would give me a 0 on the screen (even without ever defining a). In addition, QBIC initialises q-z to be 1 through 10 by default. The ? is obviously shorthand for the PRINT statement and writes to screen.

3 bytes

_Xb

_X can be used to terminate a program, and when used with a suffix, it will print something on exit. Suffixes can be A-Z (which refers to string variables A$ - Z$) or lowercase a-z (for the numerical vars of this name). The example snippet ends the program, and prints variable b to screen before it turns off the lights.

4 bytes

?_r|

_r is a random number generator. By itself, it will generate a random number between 0 and 10 and, in this case, print it. We can also add one or two parameters for a different lower and upper bound; If only one is specified, that's our new upper bound.
_r20| will generate a number between 0 and 20.
_r5,18| will generate a number between 5 and 18. The statement _R is equivalent to _r with one exception: _R assigns to a variable, _r does not:

?_r|    PRINT getNextRandomNumber(0, 10)
_R|?a   a = getNextRandomNumber(0, 10) : PRINT a

5 bytes

:_Ra|

The above snippet introduces the :, which reads the first unread command line parameter and assigns it to the first available numeric var. The resulting QBasic code for this snippet is:

a = assignCMDToNum!
b = getRandomNumber(0, a)

There's also ;, which does the same for string variables.

6 bytes

?!z$+A

Here, we see a cast in action. QBasic is kinda picky when it comes to data types. Adding a string to an integer will result in errors. To work around this, I've added a casting function. The above snippet will print 10 (z is auto-initialised to 10) and append whatever is in the variable A$. For instance, a full program could be

#test`?!z$+A

and the result then is 10test.

Casting is done using the ! symbol. It then casts everything between the ! and the delimiter. Usually | is the delimiter for variable-length arguments, but CAST uses either a $ to perform the cast from number to string, or another ! to cast a string to number.

7 bytes

Z=_f_tA

Lot going on here. Let's work on the assumption that A$ already holds a value, say " Hello " (significant spaces). This snippet then sets Z$ to the reversed (_f), trimmed (_t) version of A$, olleH and prints it to the screen.

  • The behaviour between _f and _F is different: _F declares a variable and assigns its output to it, _f only gives the output and assigning is done by other parts of the script. The same goes for _r in my 5-byte snippet. This is called ULX, or Upper-Lowercase Extension. Whether or not output gets auto-assigned is one of the behavioural changes ULX can bring, but there are other examples. _D, for intance, yields the system date, _d yelds system time. Both don't auto-assign.

  • _t removes the whitespace on both sides of its argument. _u does a left-trim, _v does right-trim. All three support ULX, and for all three this switches between auto-assign (uppercase) or output only (lowercase).

  • Both _f and _t should be delimited with | to signify the end of the parameter list. However, since EOF is reached, the correct number of |'s get added to close all opened parameter lists. If this statement would have been followed by the closing commands for language constructs (]or }, see byte 1) those same |'s would get added.

  • QBIC allows for the result of one function to be the input for the next: _f takes as input the result of _t

  • Finally, if we would run this program, it would actually print olleH, despite we never use a ? or _X* statement. This is because QBIC implicitly prints the contents of Z$ on exit.

Summarizing, the above 7-byte snippet would roughly compile into this QBasic block:

FUNCTION revstring$(in$)
  ... function definition imported through QBIC.H
END FUNCTION 

... we set A$ to be "  Hello  "

Z$ = revstring$(LTRIM$(RTRIM$(A$)))

PRINT Z$

8 bytes

Let's look at literals. There are 2 types in QBIC: String literals (Verbal and Silent) and Code Literals. They are started with @, # and ' respectively, are terminated with ```. Using a &boxul; respresents a line-break.

?@check`  --> Verbal string literal: Defines A$ in the header, assign the value "check" 
              to it, and insert A$ in the body of the resulting QBasic at this moment. 
#10`?A+A  --> Silent literal: Defines the literal A$ as "10", but doesn't insert `A$` 
              in the QBasic output at this time. This sample then prints "1010"; `+`in 
              this context is string concatenation.
'SQR(9)`  --> Code literal: from the `'`(which would be seen as a comment by QBasic) to
              the ``` is not stored as a variable, but passed unaltered to the resulting 
              QBasic. This particular statement calculates the root of 9.

Answered by steenbergh on November 19, 2021

StackyLogic

Factoid:

StackyLogic is originially from a codegolf challenge, as seen in the link. It consists of a series of "stacks", however there are no "push" operations.

Length 1 Snippet

<

This is not a full program at all. This is just the pointer symbol. This symbol denotes where the pointer starts

Length 2 Snippet

?<

This program takes a bit of input, and outputs it. It would be a cat program, if it looped, however Stackylogic possesses no loops.

First, the program will substitute the ? for either a 1 or 0, depending on input. Then, it will execute this command. 1 will make the pointer move down one, 0 will make it move up one. Then, upon discovering the empty stack (which are always implicitly exist), it will halt, and output the last executed command, either a 1, or 0

Length 3 Snippet

?1<

This program always outputs one, the ? is never used. This is because, as stated in the previous snippet, 1 will move the pointer down one, and the implicit empty stack will cause the last executed command to be printed. the ? isn't used, because the pointer is never directed to it.

Length 4 Snippet

?
?<

Our first program with multiple non-empty stacks.

This program outputs the result of an OR operation on two bits.

How it works:

It first substitutes the ? under the pointer with a bit from input, and executes it. If it is a 1, it will go forward, find the empty stack, halt and print 1.

?<

If it is a zero, it will go up one, and act like the above code: it will substitute the ? for a bit, execute it, and then move onto an empty stack and output it.

Note how the code after the first ? is executed is the same as snippet 2

Length 5 snippet

1
??<

This program, like the last program, outputs the OR of two bits. However, the ?s are on the same line. if the first bit is one, it will move forward on to an empty stack, output 1, if it is a 0, it will move back one, on to the one, and then move forward back on to the second ?, again being identical to the length 2 snippet. This illustrates how multiple programs can have the same effect. You might have noticed that no new language features have been introduced this time. This is because they have all been introduced.

Length 6 Snippet

1
?<
0

This program outputs the not of one bit (the opposite of snippet 2). You might, by now, think that StackyLogic is really boring, and can't do anything interesting. This isn't (entirely) true. It can be used for more interesting things, it just takes A LOT of characters. However, even after these lots of characters, it is not capable of much computation, it cannot even store the input, most challenges are closed out to it (in fact, the linked example actually checks which year it is, if it divisible by 4, to see if it is a special case (not a leap year))

Length 7 Snippet

?<
?1
?

This program "nests" an OR in a surrounding program. I say it nests it, because if the first bit is 1, it changes to be the exact same as the OR, and executes the same things. This program is (x AND (y OR z))


I don't really know anymore decent snippets, there isn't much more to show. I plan on making another answer with my derivative, Eseljik, after I actually make the interpreter, but before that decide on the final part of the spec. Anyway, there are a lot more commands in Eseljik, so I shouldn't easily run out of things to show, like I have here.

Answered by Destructible Lemon on November 19, 2021

eacal

0-vote

eacal is a language made by me in 2016. It's very extremely verbose, but, as I hope, is capable. There is one command per line, and each data entry is separated by spaces. It is meant to be classified under a lot of programming paradigms, which includes right now, imperative, structured, stack-based, object oriented, event-driven, and a tad of functional.

Fun fact: the empty program errors.

1-vote

v

This prints:

eacal is currently running.

This tells you if eacal is still alive. Helpful!

2-vote

on

This is the event-driven portion of eacal. It's syntax is:

on <event> <code evaluating to a function>

Here is an example:

on end eval print string Done!

print string Running...

This prints:

Running...
Done!

3-vote

arg

This returns all of the command-line arguments passed to the program. Like so:

node eacal.js <file> 3 4 Hello

File:

print arg

Output:

[ '3', '4', 'Hello' ]

4-vote

init

This is used to initialize stacks, like so:

init main

Otherwise, the stack does not exist.

5-vote

alias

This sets creates a command that function the same as another command. Example:

alias define_stack init
define_stack main

is the same as

init main

This is very helpful in golfing.

6-vote

string

Represents a string, where it's arguments are joined by spaces. So, Hello, World! is this:

string Hello, World!

7-vote

numlist

This returns an array of numbers representative of its arguments. For the first few Fibonacci numbers in a list:

numlist 0 1 1 2 3 5 8 13 21

8-vote

func add

This shows some of eacal's function programming. You can execute it on a stack named k using exec k--func add. For example:

init main
push main number 5
push main number 8
print exec main--func add
; outputs 13

Answered by Conor O'Brien on November 19, 2021

Your Mom

Factoid

Your Mom is a stack-based golfing language created because of a mbomb007's chat message on TNB:

I think someone should create a language called "Your Mom", just so that during an argument over which language is a better one, they can interject that "Your mom is a better language"

Source

Since Your Mom use Unicode, the length of the snippets are in characters, not bytes

Length 1

+

+ pop two values and return their sum. Since there is nothing on the stack, the two values are read from stdin.

Length 2

()

Define a empty function. ) is not needed since it's the end of the program.

Length 3

#II

# push a zero, I pop the last value, multiply it by 24 and add 18, because Your Mom use base 24. The state of the stack at the end is [ 450 ]

Length 4

¥()@

This snippet create a infinite loop.
¥ push 1 to the stack, () define a empty function and @ pop a function and call it while the element on the top of the stack is true (but don't pop it)

Length 5

çç#,.

This snippet create 2 array (ç), push 0 in the last array (,) and concatenate the two arrays (.)

Length 6

çÐ,€²Ç

This snippet create a array, push to it the user input (Ð), define a 1 character function that process the sqare of it's input (€²), and map it to the array.

Length 7

Ð(:_⊟)@

This snippet read the user input and print it, and decrement it while it's not 0

Length 8

##21®€²Ç

This snippet create a range from 0 to 20, create a one character function that square it's argument, and map on the range.

Answered by TuxCrafting on November 19, 2021

Majc (formely hashmap)

Factoid
hashmap is not necessarily a golfing language, although it's commands can make it so. (Also it's spelled hashmap, not Hashmap).
It was renamed in June 11, 2016 to Majc.

0 byte snippet:

 

This does nothing.

1 byte snippet:

.

Clear the stack... now.. there's nothing in the stack.. so...

2 byte snippet:

id

Convert input to a number, this is also the long version of h.

3 byte snippet:

h2^

h is short for id, so we're taking the input as a number and get it's squared.

4 byte snippet:

{}:a

5 byte snippet:

isrsr

Kind of lost ideas here, but i takes an input, sr reverses it.

I'm not sure if this still works but this created a code block (based on CJam) and assigns it to variable a. Code blocks are like anonymous functions (unless assigned to a variable).

Answered by user47018 on November 19, 2021

Pascal

Factoid : Pascal programming language is a very old programming language which is invented in 1970 (2 years older than C) by Professor Niklaus Wirth . Original Pascal is procedural .

Because of its easy syntax and perfect efficiency , many programs have been made using Pascal . some examples are :TeX - Apple Lisa - Total Commender - Skype

Major Implementations are : Gnu Pascal - Free Pascal - Turbo Pascal - Borland Pascal


Length 1 snippet :

.

This is a dot ! Any pascal program must end with "." even if it is possible to be terminated in the middle . This dot is usually written after an end . To terminate the program somewhere at the middle of execution , you need to use halt command

;

This is not a snippet , I've just mentioned it for its importance . this is an empty statement . It is so important to use it in right place . You must put this at the end of almost "every" command . but there are some execptions too . for example :

...
IF (x<=y) THEN HALT
...

is different from :

...
IF (x<=y) THEN HALT ;
...

We'll see this difference later .


Length 3 snippet :

END

This is a reserved word in Pascal . Pascal is a block-structured language - like C - which means a program is separated to blocks , and each block may be separated to some smaller blocks and so on . each block contains some statements . In Pascal , Blocks start with BEGIN and end with END (like { and } in C) . Main program is ended with END. and all the sub-programs (like functions , programmer-made procedure etc) are ended with END;.


Length 7 snippet:

PROGRAM

Sorry for the delay, fans! So, this is a PROGRAM! Every program must start with PROGRAM <name>;, where <name> is your program's name. Every program must have a "main block", which is a part of code between BEGIN & END which is not related to any other parts of code (e.g. it's not a function's definition) & program's execution starts from there.

Answered by user55673 on November 19, 2021

Golisp

Factoid

Golisp is a very simple programming language, but despite it's name it's not a Lisp dialect.

Length 1 snippet

0

Return 0, but since this value isn't used this is a no-op.

Length 2 snippet

""

Return a empty string, but since this value isn't used this is a no-op.

Length 3 snippet

(0)

Create a list with 1 element, 0

Length 4 snippet

+[1]

Call the function + with one argument, 1. The returned value is 1.

Length 5 snippet

chr@5

Use the shorthand notation function@argument. Return the ASCII character ENQ (5), but as always, nothing is printed :/

Length 6 snippet

+[3 5]

Simply add 3 and 5.

Answered by TuxCrafting on November 19, 2021

PyCal

Factoid:

PyCal is a math-based programming language written in Python, hence the name. It's designed to compete in code-golf challenges that need math.

Length 1 snippet

!

OK, let me explain a little about PyCal. PyCal has two "variables". One variable's value can be set by the user. The other variable's value comes from the values that some commands return. For example, the F returns the nth Fibonacci number.

Anyways, the ! command outputs the value that is in the user-set variable. By default, it's 0, so the above snippet outputs 0.

Length 2 snippet

IP

This snippet outputs the first n prime numbers as a list.

Let me explain what this does:

I gets input, and converts it to an integer before storing it in the variable. (From now on, I'll call the variable that the user can change "variable". The other one will be called the result. Read snippet 1 for more info)

P takes the variable's value and prints n prime numbers. For example, if the value is 5, it will output the first 5 primes.

So, here's what it will look like if the input is 10:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Length 3 snippet

(7)

Ah, it's good to be back, I took a long break.

Anyways, let's get on with the explanation. Well, this is actually really simple. It changes the value of the variable to 7. Of course, this doesn't output anything. You can add a ! to the end to output the number.

Length 4 snippet

(wip)

Length 5 snippet

(i)S!

This snippet gets the square root of the input. (i) sets the value of the variable to the input and converts it into an integer. S calculates the square root.

Answered by m654 on November 19, 2021

Desmos

Factoid: The Desmos community has a wealth of programs that use many math equations to make them work. Take, for example, this 3D visualizer.

1 byte

x

One of my favorite things about Desmos is that you can write out equations like this without having to put y= before it, as Desmos automatically does it for you.

Answered by weatherman115 on November 19, 2021

Scratch

Factoid: Scratch has a great appeal to younger audiences, with the large majority of new accounts being from 10 to 16 years old.

1 byte

Say
The say block takes what is in the text space and outputs it as a text bubble.

2 bytes

Start & Stop
The when green flag clicked block is essential for most programs. The stop [all/this script/other scripts in sprite] block does exactly what it says, but it isn't used much in optimized scripts.

Answered by weatherman115 on November 19, 2021

JSFuck

Length 5

+!+[]

As mentioned before (in the length 4 section), !+[] produces true. Also, as mentioned before (in the length 1 section), + can cast to number.

Therefore, this code casts true to number, which is 1.

This snippet can be chained indefinitely to produce any number you want.

For example, 2 would be +!+[]+!+[], and 3 would be +!+[]+!+[]+!+[].

As mentioned before (in the length 4 section), +!![] is also valid.

Length 4

!+[]

The operation ! casts to boolean.

The number 0, the empty string "", the undefined, and the NaN are all treated as false.

Other objects are treated as true.

Unlike Python, the empty array [] and the empty object literal {} are treated as true.

Therefore, this is the shortest snippet to produce true. It is equivalent to !0.

!![] would also work.

Length 3

+[]

As mentioned before, + casts to integer. In this case, it would be evaluated to 0.

However, also as mentioned before, + can join two arrays to form a string.

Therefore, +[]+[] is really 0+[] which would produce "0".

Length 2

++

There are really only 36 length-2 snippets.

Out of the 36 snippets, I chose this one.

This is the shortest way to add 1 to a number.

This function is very strange.

For example, v=1; ++v works, but ++1 does not.

For example, v=[]; ++v also works (empty array [] is implicitly cast to 0), but ++[] does not.

To make it work in JSFuck, you would have to type ++[[]][+[]] instead.

[[]][+[]] is really [[]][0], which is an empty array [].

Why ++[[]][+[]] works but not ++[] is yeond me.

Length 1

+

+ can convert a string to a number, as well as adding two arrays together to form a string. For example, +"0" would result in the number 0, and [1]+[0] will result in the string "10".

Factoid

All JSFuck programs are valid Javascript programs. However, JSFuck aims to use only 6 operators to do everything: +![](). Also, its name is derived from JS (javascript) and Brainfuck. Brainfuck only uses 8 operators.

Answered by Leaky Nun on November 19, 2021

Unipants' Golfing Language

Factoid

UGL only has 16 operations, a stack, registers, ifs and whiles to do things. But even if these supplies are to spare, anything may be possible if you do things smart enough... or not? ;-)


Length 5 snippet

IlOI:

Try it online!

This is the cat program. As you see, it is a translation of the brainfuck program ,[.,].

I captures one character, so it is the same as , in bf. O prints one character, so it is the same as . in bf. And l and : enclose a while loop, that works the same as [ and ] in bf (while the top of stack is non zero).

Length 2 snippet

io

Try it online!

This program reads and writes an integer. And guess it, it can be any length. i is greedy, meaning it will catch as long an integer as possible.

Length 1 snippet

s

Try it online!

This program sets the current register number to zero. First, let me show you an excerpt of the README for registers:

Registers

  • r - load the value in current register

  • R - save the value in current register

  • s - set current register number to top of stack

If the stack is empty, the current register number is set to zero.

Answered by user48538 on November 19, 2021

ListSharp

factoid: ListSharp is an interpeted langauge for list manipulation and web scraping, still in development yet it can already do some neat stuff!

  • syntax is heavily word based so a good amount of votes will be needed for functional snipplets

Length 4 snipplet:

SHOW

SHOW is the standard STDOUT of ListSharp and lets you display a variable in complete disregard to its type

Ex:

SHOW = "Hello world"
SHOW = {"1","2"} + "3"
SHOW = variable_name

Answered by downrep_nation on November 19, 2021

CSS (Cascading Style Sheets)

Somebody's already done a CSS answer, but here's another one. I promise to make the one-char snippet exactly the same. :)


6 chars

:hover

This is an example of a pseudo-class, which is basically the state of an element. The :hover pseudo-class applies when the element is being hovered over; some others are :active (mouse button down), :valid/:invalid (form/input is valid/invalid), and :target (element is target of current #hash-portion-of-url).

Pseudo-classes can also take arguments, for example :not(some-other-selector) and the :nth-child family: :nth-child, :nth-last-child, :nth-of-type, and :nth-last-of-type.


5 chars

--foo

CSS variables, properly known as custom properties, function like variables in other languages, only a bit more

c
 a
  s
   c
    a
     d
      i
       n
        g

to fit in better with the nature of CSS. Variables are used like this:

:root {
  --foo: goldenrod;
}

.some-element {
  background-color: var(--foo);
}

.another-element {
  background-color: lightgray;
  border: 3px solid var(--foo);
}

and var(--foo) is replaced with the value of --foo.

However, because these variables are parsed at runtime, not as a compilation step in a preprocessor such as Sass or LESS, they can be used more dynamically. For example:

:root { --foo: red }
body:hover { --foo: blue }
p { color: var(--foo) }

This will make the text in <p> (paragraph) elements red, except when the <body> is hovered, in which case the text will turn blue.


4 chars

42cm

As well as the px (pixels), em (relative to font size), rem (relative to font size of root element), vh (1/100 of viewport height), and vw (1/100 of viewport width) units, which are usually what you use, CSS also has physical units for cm, mm, and in. The only problem is that they don't necessarily represent physical centimetres, millimetres, and inches, but (device-dependent) may be relative to the assumption that 1 inch = 96px. Anyway, it's usually better to use relative units like em and rem instead.


3 chars

-o-

Browser prefixes allow browsers to implement WIP standards before they've been finalised. The idea is that if the spec changes, the old implementation's behind a prefix so the correct implementation can be done without the prefix. However, browsers are moving away from prefixes in favour of flags set by the user in the browser (chrome://flags in Chrome and about:config in Firefox), as prefixes have caused headaches when trying to ensure compatibility with old browsers.

The prefix shown above is for Opera (before it switched to using the Blink rendering engine); the other prefixes are:

  • -webkit- for WebKit/Blink (Chrome, Opera, Safari)
  • -moz- for Gecko (Firefox)
  • -ms- for that thing.

Prefixes are used like this:

.foo {
  -webkit-transform: rotateZ(30deg);
          transform: rotateZ(30deg);
}

They can also be used on selectors and property values.


2 chars

//

People ask why CSS doesn't have // comments. Well it does. Sort of.

In this blog post, Tab Atkins talks about using // comments in CSS. They don't function as line comments, but rather "next construct comments". This means that these are equivalent:

foo {
  color: white;
  // font-weight: bold;
  background-color: black;
}

// bar {
  width: 12rem;
}

// @keyframes baz {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

and

foo {
  color: white;
  /* font-weight: bold; */
  background-color: black;
}

/* bar {
  width: 12rem;
} */

/* @keyframes baz {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
} */

There are also some weird tricks like using a @comment { } block to simulate nested comments.


1 char

*

The star hack. Sample usage:

.foo {
  background-color: lightgray; /* displayed by most browsers */
  *background-color: red; /* displayed by IE <= 7 */
}

Factoid: some web servers originally served .css files as application/x-pointplus, to do with presentation software, instead of text/css.

Answered by gcampbell on November 19, 2021

Tellurium

Factoid

Tellurium is an esoteric, tape-based programming language written by me in Python. It's mainly intended for use in code-golf challenges, but it pretty much failed at that task.

Length 1 snippet

^

^ is the output/print command. It outputs whatever is in the selected cell, which, in the above snippet, is 0. (0 is the default value)

Length 2 snippet

i^

This is a simple cat program (a program that copies its input to its output). i takes input and puts it in the selected cell. As you probably remember, ^ outputs whatever is in the selected cell.

(I promise that there will be more interesting snippets later on. There's not much you can do with two commands)

Length 3 snippet

I§^

This snippet calculates the factorial of the input and displays it.

I gets input and converts it to an integer. § calculates the factorial, and stores the result in the selected cell.

There are numerous other math-related one character builtins, for example:

I½^ calculates the exponent of the input

Iq^ calculates the square root of the input

Length 4 snippet

{p}f

This is an anonymous function that does... nothing.

In Tellurium, you can create an anonymous function by using the syntax {code}f. The function can then be called using the command ä.

p is a placeholder command, the equivalent to the Python statement pass.

Length 5 snippet

[I|^;

This snippet uses a loop to output 0 n times. The syntax for a loop in Tellurium is [times|code;. If I is in the times section, it will run the code input times.

Length 6 snippet

µHi!~^

Finally, something more interesting. This snippet outputs Hi!. The syntax for inserting text into the selected cell is a bit strange: µ(text)~.

Length 7 snippet

¤h|Hey]

This snippet showcases variables. Again, the syntax is a bit strange: ¤(name)|(value)]. In this case, it stores "Hey" in the variable h.

To display that variable, use ;h.^.

Answered by m654 on November 19, 2021

Sonic Pi

Code Snippet 4:

dice

You don't see anything on the output, but if you show it with puts, it's a random number. Don't worry if your number is always the same, Sonic Pi uses the same random seed for every run, but that's good because else your songs would sound different every time.

Code Snippet 3:

:e1

This equals the MIDI-Note 52 and the frequency 164.81377845643496 hz. It must start with a : so Sonic Pi knows it's an integrated constant.

Code Snippet 2:

[]

Empty list. Sorry, nothing else except comments can be written in two bytes.

Code Snippet 1:

#

Starts a comment.

Factoid: Sonic Pi is a sound coding language and is a full valued programming language.

Answered by univalence on November 19, 2021

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 ;
…

Answered by Fatalize on November 19, 2021

GNU Octave

Snippet 7:

disp(j)
 0 + 1i

Prints j out to the screen without the ans = overhead

Snippet 6:

[i](1)
ans =  0 + 1i

This generates an instance of a scalar only containing sqrt(-1), takes the first element of it (a complex number), and prints it out. A scalar is basically an array.

Snippet 3:

{3}
ans = 
{
  [1,1] =  3
}

This generates an instance of a matrix with one entry, 3.

Snippet 2:

[]
ans = [](0x0)

This is just a simple empty array.

Snippet 1:

j
ans =  0 + 1i

Yes, Octave understands i or j as the square root of -1!

Factoid: Octave is free and approximately 80% compatible with Matlab! (except toolboxes)

Answered by univalence on November 19, 2021

Batch

Factoid

Batch uses commands that the Windows command line uses. A bunch of these were inherited from the (ancient) MS-DOS.

Length 1

:

This creates an empty label. In Batch, empty labels are perfectly legal, even if they don't do anything.

Length 2

at

This command schedules commands and programs to be run at a specified time. The batch file must be granted elevated administrator privileges for this to work.

Length 3

rem

A command that discards parameters supplied after it. This essentially comments out text.

Length 4

echo

With four characters, we can finally print text! This will print out whatever comes after it.

Length 5

start

As one of the most simple commands, this just opens up a separate command-prompt window. Nothing too complicated about this at all.

Length 6

chkdsk

This command also requires elevated administrator privileges. This command is short for "check disk". It does what it says; it checks a disk and provides a status report.

Length 7

replace

This command is used to replace one file with another. The file names are passed as parameters to the command.

Length 8

shutdown

This command can shutdown your computer. It has a variety of parameters, and like setting shutdown time, a shutdown comment, or aborting the shutdown.

Answered by ericw31415 on November 19, 2021

HQ9+

Factoid:

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

Length 1

Q

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

Length 2

9+

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

Length 3

9H9

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

Length 4

HQ9+

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

Length 5

+++++

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

Length 6

QH99QH

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

Length 7

QQQQQQQ

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

QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
(49 of them)

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

Length 8

+++Q++++

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

Length 9

BURLESQUE

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

Length 10

H+H+H+H+H+

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

Length 12

219661 beers

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

Answered by SE - stop firing the good guys on November 19, 2021

Cy

Cy is a postfix language that operates on a stack. Cy is meant to be somewhat-practical, meaning I do things like use actual words and have insignificant white space, in sharp contrast with my previous languages.


If I explain things poorly or you want to try it yourself, feel free to install the Ruby interpreter


I will be using the following format in examples (this is the format used by the Ruby interpreter's REPL (accessible via the -r parameter (ooh nested parentheticals! I should try lisp next!))):

>>> 
:: [initial stack]

>>> some code
:: [resulting stack]

>>> some more code
:: [resulting stack]

Factoid

The order in which operands are expected on the stack is based not on what makes sense, but the order in which it would be most convenient to pass on arguments in a tacit style, i.e. taking arguments in the same order as they would most likely be passed to a user-defined function. More on this later.

Length 1 Snippet

1

This pushes the number 1 to the stack.

Example:

>>>    
:: []

>>> 1
:: [1]

Length 2 Snippet

$x

This pushes the value stored in the variable x to the stack. Assigning values to variables is covered below.

Length 3 Snippet

"a"

This pushes the string "a" to the stack. Pretty self-explanatory. Note that single quotes ' cannot be used for this purpose.

Example:

>>> "a" # string 
:: ["a"]

>>> 'a' # error
Error
  @ `'a'`

Length 4 Snippet

tran

tran is an incredibly useful built-in I just implemented. This operator is used to define a stack transformation. It takes two arrays describing the old and new state of the stack. The second array should be a shuffled version of the first, and the stack will be modified accordingly.

Example:

>>>
:: [1, 2, 3, 4]

>>> [.a, .b] [.b, .a] tran
:: [1, 2, 4, 3]

>>> [1, 2] [2, 1, 2] tran
:: [1, 2, 3, 4, 3]

Length 5 Snippet

10 =x

This is the syntax for setting variable x. Note that the = sign has to be touching the identifier; 10 = x would do something different.

Length 6 Snippet

&print

Now we get into the interesting stuff. print is a function that pops something from the stack and outputs it. & is a prefix that makes its function peek from the stack instead of popping it. This means that the top of the stack will be outputted, but still left on the stack.

Length 7 Snippet

{10} if

This showcases two things - blocks and if-statements. A block holds a piece of code. The block {10} is a block that pushes 10 to the stack. The if command pops a value from the stack, and if it is truthy, executes the given block. In this case, it would push 10 to the stack.

Example

>>>
:: [0]

>>> {10} if
:: []


>>>
:: [1]

>>> {10} if
:: [10]

Length 8 Snippet

{3 2 ^-}

This demonstrates another modifier, related to &. Without the ^, the block {3 2 -} would just push the difference of 3 and 2 (1). However, the ^ in front of - makes it do something special. If the block is called with an &, it will execute &- (peek for operands); if not, it will execute - (pop the operands).

Example

>>> {3 2 ^-} =f
:: []

>>> f
:: [1]

>>> &f
:: [1, 3, 2, 1]

Answered by Cyoce on November 19, 2021

Racket

We have Clojure (the Java among LISPs), and Common Lisp (C), but where are Scheme (x86 asm) and more most importantly Racket (Python)?? :o

Racket is like the Python of LISPs. Common Lisp seems old (it's older than FORTRAN!), and Scheme seems boring, academic, and comes with a too-sparse standard library.

On the other hand, Racket is a batteries-included, industry-ready Scheme, that's fun to learn and use every day.

Factoid

In most other LISPs, () is the empty list. However, Racket's syntax is minorly deviant in that '() is the empty list and () is an illegal empty application (that is, the application of nothing to nothing, which makes no sense).

Length 1

λ

Other people have been counting chars not bytes so I'll use this two byte unicode glyph: U+03BB GREEK SMALL LETTER LAMBDA. This is synonymous with the lambda keyword for creating anonymous functions, which is excellent for golf because otherwise, you'd need to (define (name args...) exprs...) which is longer. (Of course, Racket isn't very golfy otherwise.)

Length 2

#f

False. #t is for true, and so is everything that's not #f, much like other functional languages, and much to the dismay of every imperative programmer ever.

Length 3

let

Another keyword. (Still no executable code.) This one is an integral part of any LISP; it lets us define local variables and procedures.

A let form looks like:

(let ([a 1]
      [b 2])
    (displayln a)  ;; 1
    (displayln b)) ;; 2
(displayln a)      ;; error, a is not defined

Or like:

(let loop ([a 1])
    (displayln a)
    (loop (+ 1 a)))

That counts up forever, and will not cause a stack overflow because Racket is tail-recursive, like any compliant Scheme.

Length 4

cadr

One of my favourite things about Racket is this:

enter image description here

Now, car is the LISPism for Current Address Register, or the first item of a pair. LISP lists are singly linked lists like so:

'(1 2 3)
;; is actually
(cons 1 (cons 2 (cons 3 null)))
(car cdr = (car cdr = (car cdr = null))) 
;; i.e.
struct Node { int data; Node* next; };

Each item in the list is actually some data, and (a pointer to)another list, which is (a pointer to)another list, which is a... yeah.

To get the cdr (Current Decrement Register) of a given cons cell you use... the cdr function.
How to get the second item in a list? (car (cdr xs)). Or: cadr.
How to get the third item in a list? (car (cdr (cdr xs))). Or: caddr.
How to get the fourth item in a list? (car (cdr (cdr (cdr xs)))). Or: cadddr.

See where this is going? Not often are these actually used over numeric indexing, but they are very handy.

Answered by cat on November 19, 2021

Cheddar


Cheddar is a high-level, functional + object-oriented programming language designed to make programming easier, faster, and more intuitive.


Due to the fact Cheddar is still in development, running Cheddar programs can be rather difficult. Ping me in chat, @Downgoat, and I'll help you test this stuff out.


Factoid

Despite Cheddar's tasty name, it is not edible, if you'd like to eat Cheddar, please go to your local grocery store, not the Github.


Length 1 Snippet

1

This is a number. You probably guessed that but Cheddar's numbers also have some cool features:

0b1011  // Binary number
0o1337  // Octal number
0xFFFF  // Hexadecimal number

123_456_789 // One hundred twenty three million, four hundred thousand...
1.333333333 // Decimal number (yes this is a regular old floating point)

Length 2 Snippet

[]
""
''

These all create iterables. The first is an array []. The second and third are strings. In Cheddar strings may have literal newlines in them.

Length 3 snippet

|>9

This creates a range from 0 - 9, it is represented as an array so you can iterate over it, reverse it. Do anything you want!

Additionally you can use binary |> to generate a range from [a, b]

 0|>4

the above generates: [0, 1, 2, 3, 4]

Length 4 Snippet

true

This creates a boolean with a value of true. This isn't very interesting, unfortunately.

Length 5 Snippet

1?2:3

This is the ternary operator. This is the same as the following:

if (1) { 2 } else { 3 }

The difference is the ternary is an expression so rather than doing:

var a: String
if (goat.type == saanen) {
    a = "bleeeeeet"
} else {
    a = "baaaaaa";
}

You can do:

var a: String = goat.type == saanen ? "bleeeeeet" : "baaaaaa"

Length 6 Snippet

(a)->a

This, obfuscated looking code is actually very simple. It defines a lambda, or anonymous function taking one argument, a, and returns it. Note the parenthesis are optional, the following is just as valid:

a->a

Now, if you were to call foo, it would return the value passed:

print foo(123) // prints `123`

Length 7 Snippet

var a=1

This is the shortest assignment in Cheddar.

Additionally other ways of declaring variables

const foo = bar        // constant
const foo: String = bar // Same but requires `bar` to be a specific type
var foo = bar       // Can be changed, so can the type
var foo: String = bar // Can be changed but only to another string

Length 9 Snippet

String::9

This shows a cool feature of Cheddar's called casting. Classes each have defined behavior for when any class (in this case Number), is cast to them. This would output "9";

In this example String's Number cast is called which in turn casts to a string. You an also swap this around to do a number cast:

Number::"9"

which would output a number 9.

In the event a cast fails, Cheddar throws an error. I'm planning on adding an operator castable which checks if a certain value (LHS) can be cast into (RHS). Which would work like:

if foo castable Number
    print Number::foo

Answered by Downgoat on November 19, 2021

Ouroboros

Each line of an Ouroboros program represents a snake eating its own tail, with the beginning of the line being the head and the end being the tail. The only control flow operations are commands to eat or regurgitate characters of the tail. When the instruction pointer reaches the last part of the line that hasn't been eaten, it loops back to the beginning. To stop execution, simply swallow the instruction pointer.

Factoid

Ouroboros has a Stack Snippet interpreter.

Length 1

n

Outputs the top of the stack as a number. An empty stack is treated as if it contained infinite zeros, so this outputs 0. No characters are ever eaten, so the program loops (and prints) infinitely.

Length 2

1(

Pushes a 1 and then uses ( to eat that many characters from the end of the snake. This means eating the last character. However, since that's where the instruction pointer currently is, the snake dies and the program terminates.

The program would also terminate if the number were 2, or indeed any larger number; in that case the entire snake would be swallowed. (Physically impossible, but hey--this is a metaphor.)

Length 3

32n

Although Ouroboros processes one character per tick, it still supports multi-digit numbers in the expected way. This program will push and output 32 infinitely (rather than, for instance, pushing 3, pushing 2, and outputting only the 2).

One interesting side effect: a multi-digit number is recognized as such even when it bridges the end of the snake. The code 2n3 will first output 2, but thereafter will output 32 infinitely.

Length 4

rnao

r reads a positive integer from input, grabbing all contiguous digits until it finds a non-digit. n outputs as a number. a pushes 10, and o outputs this as a character (newline). Thus, an input of 1 2.3 -4abc55 will yield

1
2
3
4
55

However, because this snippet doesn't terminate the loop when the input is used up, the program will continue: r will start giving -1s to signal end-of-input, and n will keep outputting them indefinitely.

Length 5

n?2*(

Prints one or more 0s, with the exact count depending on random numbers.

n behaves as in snippet 1, outputting a 0 from the empty stack. ?2* generates a random floating-point number between 0 and 1 and doubles it. Then ( eats that many characters (rounded down). Thus, if ? generated a number >= 0.5, the program halts; if not, it loops, prints another 0, etc.

Length 6

"oooo(

" toggles between executing characters and treating them as a string. As in other 2D languages, you can define a string using only one quote mark because the instruction pointer wraps around. A key difference with Ouroboros, however, is that the string is pushed in reverse order, so that the first character is on the top of the stack. This means we don't need to write strings backwards or have a stack-reverse operator like ><> does.

The above code pushes "oooo(" and outputs the first four characters (the os). It then uses the last number remaining on the stack (40, the charcode of () as the argument to the ( command. Eating 40 characters definitely swallows the IP, and the program halts.

Length 7

r.*.n!(

Truth machine program.

r reads a number from input, or -1 for EOF. .* multiplies it by itself, keeping 0 and 1 the same but mapping -1 to 1. .n dups and outputs the number. Finally, !( logically negates and eats that many characters of the end of the snake. If the number was 0, this eats the ( and dies. If the number was 1, this eats zero characters, and execution loops back to the beginning of the snake, printing 1 indefinitely.

Length 8

i.0<2*(o

Cat program.

i reads a single character from input, pushing its charcode (or -1 on EOF). .0< duplicates and tests if the value was less than 0; i.e., pushes 1 on EOF and 0 otherwise. 2*( multiplies by 2 and swallows that many characters. On EOF, this eats (o and ends the program; otherwise, nothing is eaten, and o outputs the character from input. The snake then loops back to the beginning.

In writing this snippet, I realized that cat can actually be done in four characters: i.)o. Go read the explanation on that answer for some crazy abuse of undefined behavior.

(Length 9 snippet pending)

Length 10

[email protected]+

Outputs the Fibonacci sequence, starting from 0 and continuing indefinitely.

First, we need to initialize the stack by pushing a 1. The trouble is that any initialization code at the head of a snake will run every time through (since it's at the head, we have no way of eating it). Therefore .!+ is designed to turn the top of the stack into a 1 iff it was previously 0 (which is the case when the stack is empty). .! dups and logically negates (1 if the value was 0, otherwise 0), and + adds that result to the top value.

(For a version that uses a second snake to perform the initialization, see the GitHub readme.)

Now the bulk of the program. Call the two numbers on the stack x and y, where x is smaller and y is on the top of the stack. [email protected] copies y, rotates x to the top, and outputs a copy of it. ao outputs a newline (as in snippet 4), and + adds x to a copy of y. Now the stack contains y and x+y, and we proceed to the next iteration.

Answered by DLosc on November 19, 2021

Molecule

Factoid
Molecule is the descendent of Pylongolf2, a descendent of Pylongolf which was based on CJam.

0 byte snippet:

 

This does not do anything as it is empty.

1 byte snippet:

I

I read the input.
As Molecule outputs everything in the stack once the program shuts down, this makes a decent cat program.

2 byte snippet:

()

Anything between ( and ) is looped until ! is called.

3 byte snippet:

Inh

Read the input, convert it into a number.
The h converts numbers into characters.
So you can get some funky characters by using this.

4 byte snippet:

`q`n

Now here's where you could break the program.
Molecule has a built-in reflections system that allows you to modify the source code at runtime.
`q Push the source code, `n sets the source code to itself.
From v5.5, this snippet forces the interpreter to read from the start, creating a loop.

5 byte snippet:

0(1+~)

Have your program count until it reaches Infinity.. then it crashes.
(On my computer takes about 2 minutes to crash :P)

6 byte snippet:

u10000

Print 10000. What is so interesting about this?
It's interesting because putting a simple 10000 will push 1 and 5 zeroes to the stack, while the u keyword pushes the entire number after it.

Answered by user47018 on November 19, 2021

Octave

Note:

I got to say hello to a little earthling in the delivery room a few weeks back. Although she's lighter than a ball, she takes up quite a lot of my time. I'll redirect my focus to more important things (for instance showing of the awesomeness of Octave) when I have some spare time. Until then, please have some patience =)


Octave and MATLAB are very similar, and many of the nice features flawr has showcased would be good showcases for Octave as well. I will try to avoid reusing any of the material flawr has already used.

Snippet 1:

.

A full stop punctuation is a very versatile operator, and helps solve a lot of tasks very elegant:

Snippet 2:

++

Increment operators are one of the great features in Octave, that doesn't exist in MATLAB. It's known to most programmers as languages such as C++, Java, JavaScript, PHP and Perl all support it. Nevertheless, it's awesome when golfing, and often makes Octave submissions a bit more competitive than MATLAB. x++ is 2 bytes shorter than x=x+1.

Snippets 3:

Edit: 02.05.2016 - I'll get to this ASAP!

Snippet 4:

a+a'

This is a great way to create a grid of values, similar to meshgrid in MATLAB.

a = 0:3;
a+a'
ans =    
   0   1   2   3
   1   2   3   4
   2   3   4   5
   3   4   5   6

You can of course use this with vectors of different lengths. a+b' produces the same result as:

bsxfun(@plus,a,b')

Snippet 5:

a=b=1

In Octave, you assign a value to several variables at the same time. The MATLAB equivalent is 7 bytes: a=1;b=1

Snippet 6:

Edit: 02.05.2016: Octave is way better than MATLAB for golfing. More snippets = More possibilities to demonstrate. I'll get to this ASAP!

Factoid:

Octave is known to most as a free alternative to Mathwork's MATLAB. Octave was originally conceived (in about 1988) to be companion software for an undergraduate-level textbook on chemical reactor design1

The name has nothing to do with music, but is actually the name of one of the author's former professors who wrote a famous textbook on chemical reaction engineering, and who was also well known for his ability to do quick "back of the envelope" calculations.2.

Answered by Stewie Griffin on November 19, 2021

LOLCODE

Note: I will be following previous rules of this showcase before mods stepped in, in that the length of my longest snippet will be equal to the number of votes this post has.


25 characters

HAI 1.3
VISIBLE 1
KTHXBYE

This is a complete program that prints 1 to the standard output.

24 characters

HOW IS I z
3
IF U SAY SO

Defines a function z that when called, returns 3.

23 characters

VISIBLE SUM OF a AN 32

Prints variable a plus 32.

22 characters

I HAS A var
GIMMEH var

Create a variable and assign input to it.

21 characters

VISIBLE “HAI WURLDZ!”

The LOLCODE Hello World Program!!! w00t w00t!

20 characters

I HAS A big ITZ FAIL

Creates a variable big and assigns it to FAIL, the falsy boolean.

19 characters

QUOSHUNT OF 99 AN 9

Returns 11, 99 divided by 9.

18 characters

I HAS A var ITZ 99

Creates variable var and assigns it the value 99, a NUMBR.

17 characters

O RLY?
YA RLY
OIC

Similar to the last snippet, this is a blank if statement. O RLY? takes the value in IT and tests it for truthiness. If true, it runs the code in the YA RLY block, then exits at OIC.

16 characters

WTF?
OMGWTF
OIC

A switch/case statement. Takes the variable in IT (the runtime temporary variable) and matches it up with any OMG <value> statements. Since there are none, it goes right to OMGWTF, the default statement. Since there is no code in the block, it goes right to OIC and continues with the code.

15 characters

HAI 1.3
KTHXBYE

The shortest complete program. All LOLCODE programs start with a version number and end with KTHXBYE.

14 characters

DIFF OF 9 AN 6

Returns the difference of 9 and 6

13 characters

CAN HAS TIME?

Imports the library TIME if it exists.

12 characters

GIMMEH INPTZ

Gets input from STDIN and saves it to the already-defined variable INPTZ.

11 characters

OBTW
C
TLDR

A multi-line comment (C is the content)

10 charaters

VISIBLE 10

Prints 10 to STDOUT.

9 characters

I HAS A Z

Creates a variable called Z.

8 characters

VISIBLE 

(note the trailing space) Prints… nothing.

7 characters

HAI 1.3

The hello() of LOLCODE.

6 characters

GIMMEH

A function asking for input from STDIN. This does nothing as it's not assigned to a variable though.

5 characters

Y R 6

Assigns the NUMBR 6 to the already-defined variable Y

4 characters

":)"

A newline inside a YARN. THE : character is the escape character inside strings.

3 characters

BTW

An empty comment. w00t.

2 characters

""

An empty YARN

1 character

I cantz do real stuff with my 1 char!!

-- Hohmannfan

3

It da NUMBR 3.

Factoid

Is composed almost completely with Internet slang.

Answered by OldBunny2800 on November 19, 2021

MIPS

Factoid: Though many see MIPS's heyday is in the past with ARM taking over the market, the classic RISC design often taught in universities continues to be widely used in embedded devices and newer small devices in Asian markets.

Length 1

Being assembly, not much can be done in one instruction. That being said, MIPS does offer an interesting native (not psuedo-) instruction: BGEZAL, Branch on greater than or equal to zero and link.

Hex code      Syntax
0x05110000    bgezal $t0, label

Answered by qwr on November 19, 2021

Quetzalcoatl

6 snippet:

{c.I?}.

Makes a block with Code Snippet 4.

5 snippet:

{c.I}

Makes a code block, containing the code c.I. On snippet 8, we will use this.

4 snippet:

c.I?

Same as before, but also does power. Result is xth root of x.

3 snippet:

c.I

Outputs (input, 1/input) because I in 1/.

2 snippet:

c (or any token) + -q compiler flag

Proper quine. -q outputs source instead of running code.

1 snippet:

1 or (no code) + -n (1 byte).

Like in GolfScript, numbers just push their value. This outputs 1 because Quetzalcoatl implicitly prints the stack. This works for any digit 0-9. Second snippet outputs Quetzalcoatl, because -n outputs Quetzalcoatl.

Interesting fact:

Quetzalcoatl got its name from the Aztec snake god (I wrote it).

Answered by NoOneIsHere on November 19, 2021

Detour

If you're having difficulty understanding any of these concepts (or, more likely, if I'm explaining them poorly), please feel free to try it yourself on the online interpreter which gives a nice visualization of the data moving around. There is also a TIO site but it doesn't have a cell visualization tool

Summary

Detour is a 2D language I made. While most 2D languages revolve around directing the instruction pointer (think ><>, befunge), this one focuses on redirection of data/objects. Each character in the program translates to a cell. Each cell will either simply pass on its contents (NOP), modify its contents and pass it on (operations such as addition), or redirect its contents (e.g. pointing its contents downward). More on this later.

Factoid

Detour got its name from the "control flow" in the language. I often find myself constructing complex paths to make data travel around the existing data flow, hence "Detour". This is the purest form of spaghetti code.

Length 1 Snippet

:

: specifies where input is taken. At the start of the program, all input arguments are pushed to the : cell, and then start moving rightward. If no : cell is found, one is inserted by default somewhere (usually at the top or middle).

Length 2 Snippet

+.

This is a program that adds two numbers and outputs the result. The . outputs its contents; that's pretty simple. The more complex part would be +. + is a binary operator which, as you would expect, adds two numbers. The way it adds them, however, is a little weird. In Detour, an operator that takes multiple operands will wait for all its operands to be in the cell before performing the operation.

So let's say a 3 is pushed into a + cell. That 3 will stay in that cell until a second number is also pushed into the cell. After our program does its thing, eventually a 4 finds its way into the same + cell. Now, it has two operands, and will happily add them together and push the result (7) into the next cell.

In this case, the next cell is .. Once the two input arguments get onto the + cell, their result is pushed to ., which outputs the result and exits the program.

Length 3 Snippet

$<<

Ok, now it's starting to get interesting. < is the decrement operator, so it takes n and pushes n-1 to the next cell. $ is the duplicate operator, it clones its contents, pushing one to the next cell, while the other skips the immediate cell. The first clone usually will then also hit the second cell.

Example:

$<<
4

$<<
 44

$<<
  33

$<<
   23

As you can see, $<< yields n-2, n-1. I use this in my fibonacci sequence answer

Length 4 Snippet

[<,]

Now it starts to get interesting. [] denotes a loop; that is to say, data will pass through it until it is negative or zero. The body of the loop, <, does two things: 1) decrement the number; 2) output it. For example, 4[<,] will output 3210

Length 5 Snippet

[$<<]

Now we get to start combining previous snippets (I know, a bit cheaty, but it's late and I'm tired). Remember how in the length 3 snippet we discussed how n$<< yields (n-2, n-1)? Now imagine if we repeatedly run that process over all generated n until they are all ≤ 0? We get the fibonacci sequence!

Warning: the produced results will be negative. Take this into account before using this sequence for something that may pertain to black holes

Length 6 Snippet

g>d$G+

This calculates, given n, n + (n + 1) / 2. While this is not very useful, it demonstrates an important concept: registers. g stores a value in the register, while G retrieves it. What happens is the number gets stored in g. Then it walks through, getting incremented (>), cut in half (d), then duplicated ($). The new value ((n+1)/2) gets added to the value stored in g (n). This yields n + (n+1)/2. Here we start getting into the complicated stuff that's hard to explain with words, feel free to try it in the interpreter.

Registers are used in my fibonacci sequence answer (the 30-byte solution) to store the value of sqrt(5).

Length 7 Snippet

<Q.
;d<

This is again kind of nonsensical, but demonstrates two key components of Detour.

  1. Control flow (Q)
  2. Recursion (;)

First off, Control Flow.
As mentioned in the intro, control flow in Detour is pretty nonstandard. In Detour, control flow cells manipulate an object's direction or location rather than its value. We have seen some control flow in the form of $ and [].
As in the example, Q conditionally redirects objects: that is, it will move an object depending on the object's value. In Q's case, it will push the object down (put keep it pointed in the same direction) if it is positive, and will push it forward otherwise.

Recursion (;) is another type of control flow. ; will move an object to the start of the program (where the input came through, or more concisely, the location of the : cell).

Combining these two things, we can see what the snippet does

  • take input n
  • decrement it
  • If n >= 0, push it down
    • halve it, then decrement it and move it back to the start (lines wrap around in Detour making ;>d equivalent to >d;)
  • Else, push it forward
    • output it.

This can be translated to the following Python program:

def f(n):
  n -= 1      # <
  if n <= 0:  # Q
    print(n)    # .
  else:       # Q
    n /= 2      # d
    n -= 1      # <
    f(n)        # ;

f(input())

Length 9 Snippet

<Q>S.
;$<

This is a recursive fibonacci definition. S sums up all items pushed to it. The bottom uses the fact that objects can wrap around the edges, so ;$< is identical to $<; with a leading space.

Answered by Cyoce on November 19, 2021

Reng

5-vote

1¶:+!

This uses an intersting feature: default stack pop override! pops n and sets n to the default value when popping from an empty stack. (This is 0 by default.) What this code does is initially lay down a 1, sets that as a default pop, : duplicates value (getting default pop) and adds it with the default pop, leaving twice the default pop on the stack. ! skips the 1 instruction, and sets the default pop to twice what it was.

4-vote

is~o

This is a cat program. It takes input (i), s jumps if the byte != -1, and o outputs. When reading EOF for input, -1 is put on the stack, and the program terminates.

3-vote

9#q

This stores the number 9 in the variable q.

2-vote

{}

Reng has codeblocks! This pushes an empty codeblock to the stack. Forever.

1-vote

~

This ends the program.

0-vote

Reng is like ><>, but with some more functionality. Not made for golfing, as you may come to see... ;)

Answered by Conor O'Brien on November 19, 2021

WireMod Expression 2

Length 1

#

This a comment in E2.

Length 2

?:

E2 supports a the ternary operator. Really useful.

Length 5

#[ ]#

E2's multiline comments are formatted as such

Factoid

Expression 2 is a programming language inside Lua, inside a game.
(Page takes a while to load)

Answered by TickTock on November 19, 2021

IPOS

Factoid

IPOS is a stack-based golfing-language for string processing. An IPOS program places it's input on the stack at the start and prints the concatenated stack contents at the end. This has the nice side-effect that a zero byte IPOS program is equivalent to a basic cat-program.

Length 1

L

IPOS has a set of predefined variables. This program pushes the value of the variable L to the stack which is the alphabet in lowercase letters. Remember that any input string gets placed on the stack initially. So this program appends the lowercase alphabet to the input and prints it.

Length 2

SA

This program takes a string with space-separated words and sorts them in ascening order. For example the input Programming Puzzles & Code Golf yields the result & Code Golf Programming.

How this works
The input string is already placed at the stack. We push a space (variable S) to the stack and apply the command A which splits the input on spaces, sorts the resulting substrings in ascending order and joins the result back on spaces.

Length 3

'A=

As mentioned in the first program, IPOS has a set of predefined variables. If you want to define a custom variable, you can do that with the = command. It creates a new variable with the name given in the top stack item and assigns the value given by the stack item below that.

Variable names can only be one character long. Also they overwrite the original meaning of this character which means that we can no longer use A for sorting as we did in the program with length 2.

So this program simply takes the input and saves it in a variable named A. Since you usually need this value right away, = also leaves the assigned value on the stack, so the output of this program is identical to the input.

Length 4

P!r%

This program takes an input string and reverses each substring between dots. So the input abc.def.ghij yields jihg.fed.cba.

Straight to the code breakdown this time:

P!r%

P      # Push a dot '.', one of the predefined variables.
 !r    # Push a command that reverses a string
   %   # Split the input on dots, apply the reverse command to every substring 
       # and join the resulting substring back on dots.

This shows one of the commands for functional programming. Those make use of command objects that are basically strings which get treated as IPOS code. They can be created like normal strings, but instead of quotes, we use backticks for them. To create a command object with only one command we can just put a ! before it.

Length 5

S'+Re

This program takes a string of space seperated numbers and outputs their sum. Pretty simple task, but the way it does that is quite interesting.

IPOS does not have any builtins for math operations besides simple incrementing and decrementing. It is still a language for string processing, so I didn't see a reason to include those. However, we can make use of the eval command e to do some basic math. This command takes a string and performs the numeric calculations in it using Python syntax.

You might already suspect where this is going. The above program simply replaces spaces with pluses by pushing a space and a plus character and applying the replace command R to them and the input. The resulting string then gets evaluated by e which yields the expected result.

Length 6

S`2<`%

This program takes a string of space separated words and removes all but the first two characters from them.
We are using % again here which splits the input on a given character (here space), applies a set of commands to each part and joins the parts back. As mentioned above, command objects can be created just like a string, but are enclosed in backticks. The command we are applying to each part here is 2< which takes the first two characters of a string and discards the rest.

Length 7

SC/eCPj

This program takes a string followed by a space and a number, splits the string into that many pieces and joins the result back on dots.

SC       # Split input on spaces
  /      # Swap the two top stack items so the number is on top
   e     # Convert the number into an integer
    C    # Split the string into pieces and pushe the substrings to the stack
     Pj  # Join the whole stack on dots

Answered by Denker on November 19, 2021

Retina

Factoid:

Retina is based on regular expressions, and supports various stages like match, replace, split, grep, antigrep, transliteration, and sort.

0 bytes:

Counts chars in input...+1!

1 byte:

1

Counts the number of 1s in the input. Pretty boring, but can make quick unary to decimal conversion.

2 bytes:

.+

Outputs the number of lines in the input.

3 bytes:

d

Deletes numbers. (Tip: If you want empty lines to show in code, use <pre> tags.)

4 bytes:

1
$_

Computes squares. (Unary in, unary out)

5 bytes:

T`l`L

UPPERCASES YOUR TEXT.

6 bytes:

G`cats

Finds the [cats]

7 bytes:

d
$*
1

Sums digits in input.

8 bytes:

^
1
1
$'

Computes triangular numbers. (Unary in, unary out)

9 bytes:

(.)1+
$1

Dereplicates chars.

10 bytes:

S`.
¶+
$.0

Counts chars in a slightly weird way. (The shortest way is 3 characters.)

11 bytes:

(^x|1xx)+$

Matches squares.

14 bytes:


(*S1`
(*S1`

The shortest Retina quine.

15 bytes:

1
$`$'2
2
$_1
1

Computes cubes. (Unary in, decimal out)

Answered by CalculatorFeline on November 19, 2021

Fuzzy Octo Guacamole

Factoid:

Do to the longness of the name, Fuzzy Octo Guacamole is also known as FOG, and rarely Fuzztoguac.

Length 1:

:

Prints [], which is the empty stack. As you may guess, : prints the stack.

Length 2:

_;

Prints 0 because popping (_) from an empty stack gives 0. ; prints.

Alternative:

^=

This is the sign function. It returns 1 if x > 0, 0 if x = 0, and -1 if x < 0. It prints due to implicit output.

Length 3:

^_;

A simple cat program. The ^ gets input.

Alternative:

^d*

Prints n2 if n is a number, else n.

Alternative:

(^)

A infinite cat program, shortened. Loops have implicit output due to a bug tagged wontfix.

Length 4:

(_;)

Prints 0 forever. The ( and ) denote the start and end of a infinite loop, and the _; pops from the empty stack (giving 0) and prints.

Alternate:

_UNK

Also happens to be a quine. _ sets the temp var to 0, U pushes 0, and N pushes None. The K prints _UNK.

Alternate #2:

(+X)

Counts up forever, printing each number. Swapping the + and X makes it start at 0.

Alternate #3:

?

Prints a goat out of ASCII art. Thanks to @Downgoat for this suggestion.

                      ___.
                     //  \
                    ((   ''
                     \__,
                    /6 (%),
                   (__/:";,;--____----_
                    ;; :';,:';`;,';,;';`,`_
                      ;:,;;';';,;':,';';,-Y
                       ;,;,;';';,;':;';'; Z/
                       / ;,';';,;';,;';;'
                      / / |';/~~~~~';;'
                     ( K  | |      || |
                      _ | |      || |
                       Z | |      || |
                          L_|      LL_|
                          LW/      LLW/

Length 5:

^{i}:

Prints a list with the input if it is truthy, or another truthy value of the same type as the input. e.g. 1 -> [1], 0 -> [1], asd -> [u'asd'].

Note: The u is due to unicode formatting.

Alternate:

^^s=i

Outputs True if the 2 inputs are equal, else False.

Alternate #2:

^s^$:

Prints inclusive range of the 2 inputs, so 2, 4 gives [2, 3, 4]

Outputs [] if input 2 > input 1.

Length 6:

^![_;]

Prints your input as many times as itself. i.e. 3 -> 3n3n3n, 1 -> 1n, as -> adnasn. The last one is because the counter sets itself to the length of the ToS if it is a string.

Length 7

^X({@})

This is a truth machine. The ^ gets input, the X prints the ToS without popping (equivalent to o;), and the ({@}) ends the program if the ToS is 0.

Alternate:

#--repl

This starts the REPL, which is like a infinite prompt for code. But the stack is persistent, and implicit output always applies.


At this point in time, many changes were made to Fuzzy Octo Guacamole, including a REPL, implicit output and the X command.

The older snippets are staying the same, but I am adding a new alternative snippet for each length.


Length 8:

$--!++[*]

This works either as a function (add a ^ before), or in the REPL. (type the number, hit enter, paste this, hit enter).

Length 9:

2pP*.2P**

This calculates the area and circumference of a circle, assuming each stack has the input already. In the REPL, this can be done with ^C. The results are left on the stacks.

Length 10:

22^p2^pSpX

Output the product of the difference and the sum of two inputs, squared. (From a CMC (chat-mini-challenge) by Conor O'Brien)

2 pushes 2 to the stack, then 2^ pushes 2 and gets input and p raises it to the 2nd power (because of that 2 we pushed).

The same is done again with the 2^p.

Then we subtract the squared numbers we got, and square them (using that first 2 we pushed at the beginning). Finally, X peeks and pops.

This uses the difference of squares formula, (x - y)(x + y) = x^2 - y^2.

Length 11:

"Hello, "^j

Prints Hello, <input>. Pretty simple.

Answered by Rɪᴋᴇʀ on November 19, 2021

Cookie

Cookie is still in development, so these may not work!

Factoid: Cookie's name is inspired by @Dennis Jelly, and I wanted to keep with the sweet food thing. However, I forgot browser cookies, and you will be unable to find it on Github easily.

Cookie is stack oriented, and uses Javascript - specifically Node.js

1 byte snippet:

p

Checks if the number is prime, and outputs true or false.

I was really tempted to also add these two snippets:

c

and

C

Both do similar things. s converts a character to a ASCII number, while S does the reverse.

2 byte snippet:

))

Yup, it's a double increment. ) increments the stack value by one.

3 byte snippet

wJ"

Not much here. w starts a write and " closes it, so J is written.

A polite request, please don't ask me why I chose J. :P

Answered by user51533 on November 19, 2021

MATL

Factoid

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

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

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

Length 1: sum of elements in an array

The program (try it online!)

s

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

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

Length 2: sum along columns

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

Xs

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

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

Length 3: ternary range

3$:

Try it online!

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

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

Length 4: multiplication table

The code (try it online!)

:t!*

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

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

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

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

Length 5: display "all" even numbers

`@EDT

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

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

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

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

Length 6: Separate primes from non-primes

tZp2#)

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

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

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

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

Length 7: Separate digits from non-digit characters

t4Y2m&)

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

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

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

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

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

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

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

Length 8: filter square-free numbers

The code

"@YfdA?@

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

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

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

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

>> matl -e "@YfdA?@

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

Length 11: Matrix multiplication, manually

7L&!*Xs6Be!

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

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

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

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

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

Length 12: show a simple image

The code

:i:!+t0)/3YG

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

enter image description here

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

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

1 3 5
2 4 6

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

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

Answered by Luis Mendo on November 19, 2021

Jelly

Factoid

Jelly is inspired by J and, in particular, its trains. Everything in Jelly – including literals – is a link (function), and you can combine several links by simply chaining them together.

As a tacit language, Jelly programs usually do not require variable references. Also – like J – many of Jelly's atoms (built-in functions) vectorize automatically. This makes Jelly fairly competitive in code golf competitions.

Length 1

b

This full program is a neat little base conversion utility. It takes an integer n as left and a base k as right argument (resp., first and second command-line argument) and converts n to base k.

Now, since integer-to-base conversion only makes sense if both arguments are numbers, the atom b vectorizes with depth 0, meaning that it "searches" for corresponding numbers in b and k.

For example, [n1,n2] b [k1,k2] converts n1 to base k1 and n2 to base k2, while [n3,n4] b k0 converts both n3 and n4 to base k0. Moreover, the list don't have to be rectangular. Combining the two previous examples, [[n1,n2],[n3,n4]] b [[k1,k2],k0] gives the same results as before.

Try it online!

Length 2

»

Aside from atoms, Jelly has quicks. While a few of them are similar to atoms and simply execute some code, the vast majority affect the behavior of one or more atoms to their left.

For example » on its own is a dyadic atom that returns the maximum of two numbers. The quick pops the link » from the current chain and pushes the quicklink » in return, which performs a cumulative reduce by maximum, i.e., it computes the cumulative maxima of a list of numbers or characters.

For example, [n1,n2,n3,n4] » computes max(n1), max(n1, n2), max(n1, n2, n3) and finally max(n1, n2, n3, n4), and returns the list of all four results.

Try it online!

Length 3

+×_

Any chain of links is parsed in a particular fashion, which depends both on the arities of the involved links (i.e., the number of arguments they expect) and the arity of the chain (i.e., the number of arguments passed to the chain).

If the above full program is executed with two arguments a and b, sum, multiplication and difference are all dyads, +×_ becomes a dyadic fork; the outmost links are evaluated first, then the inner link is called on both results. In this particular example, the result is (a + b) × (a - b) = a² - b².

Try it online!

If the program is executed with a single argument c, each of the links in +×_ is a monadic hook, meaning that is gets called with te previous return value – initially the input argument – and the input argument. Our example thus computes ((c + c) × c) - c = 2c² - c.

Try it online!

Length 4

’!²%

This full program – intended to be run with a positive integer (or a list of positive integers) as sole argument – is a primality test based on Wilson's theorem, which states that an integer n > 2 is prime if and only if (n - 1)! ≡ -1 (mod n).

Since (-1)² = 1 and (n - 1)! is divisible by n is 1 or composite, ((n - 1)!)² % n is 1 if n is prime and 0 otherwise.

The code consists of three monadic atoms (decrement, factorial, square), which are parsed as atops (i.e., they are applied one after the other, each on top of the previous one), and the dyadic modulus – a hook – which gets called with the previous return value and the original n as left and right arguments.

Try it online!

Length 5

“wat»

Jelly has built-in string compression. While it has a few limitations – only produces printable ASCII and only compresses dictionary words – it performs rather well under these conditions.

The characters between and » are replaced with their indices in Jelly's code page, which are then interpreted as the as digits of a bijective base-250 number. In turn, this number arithmetically encodes either an index in the dictionary of short or long words, or a single printable ASCII character.

All arbitrary sequences of Jelly's code page's characters decode to something; the example string wat is decodes to the following.

 stickup Aachen

Try it online!

To compress strings, you can use this script by @Lynn.

Answered by Dennis on November 19, 2021

Factor

Factor is a concatenative, stack-oriented and object-functional programming language first developed by Slava Pestov in 2003 as a scripting language for a game engine. Factor unites the simplicity and durability of Forth's stack-procedural paradigm and extensible word-based syntax, with the applicative, point-free and functional styles of Joy and Lisp.

In Factor, whitespace is the apply operator, the default operation. All words are first class objects; in fact, almost everything is a first-class object which means tons of possibility for extensible syntax, new types and literals, and all the other awesomeness introduced by Homoiconicity.

Unlike Forth, Factor prefers to use the many, many different higher-order words at its disposal over shuffle words, which should be avoided for the sake of readability and idiomaticity.

You can download a Factor binary, or find Factor in active development on GitHub.

Oh, its documentation is amazing, and the Listener UI / IDE (written in pure Factor) has the documentation offline and searchable. :D

I mentioned above that Factor was a scripting language -- that was back when it ran on the JVM, too. Factor, its runtime and its optimising native-code compiler are 97% pure Factor, with just 3% being low-level C++ for the VM and bootstrap.

I guess we'll go top-to-bottom, Iunno.

Link to this answer, Link to Edit.

Length 1

For length 1, let's start at the most basic building block of Factor: the word that lets us make more words.

Factor's pretty verbose so there's not much to do with one byte, because the "words" are literally words, and there's a lot of whitespace everywhere.

This means the fun in golfing comes not from shortening identifiers, but from re-Factoring, which is where Factor gets its name. :D

Factor gets a lot of its pleasant syntax from Forth. The simplest flavour of word-definition word, : is an example.

Use it like:

: word-name ( input -- output ) word-body ;

The word will then be callable by word-name, and word-body will execute, taking and putting things to and from the stack. word-name's stack effect must match its actual effect on the stack. If add takes two numbers from the stack and adds them together, leaving the result on the stack,

: add ( a b -- x ) + ;

Then its stack effect is that of the only word in its body (part of the power of concatenative languages). The identifiers in the effect don't matter, just that they are a proper representation.

Length 2

Another word-definition word, ::, allows the use of the :> lexical-variable-binding word, and causes inputs to be bound to the names in the stack effect.

:: join-strings ( a b -- x ) a b suffix! ;

To bind a value to a name:

:: var-demo ( a b c -- ) a c + b * sqrt :> val ;

val goes out of scope when the word is done executing.

Length 3

[ ]

Here, I'll let you have a guess at what this is. Hint: It's not an array.


You don't know? It's a quotation -- it allows putting an executable block of literal code on the stack, that the higher-order functional and applicative words can manipulate.

Brackets for blocks come from Smalltalk syntax (with the locals vocabulary you also get [| param | code ] which kind of resembles Smalltalk's [ :param | code ]).

Length 4

I'll try to do something more interesting this time, as fede s. suggested in the comments:

2bi@

Before I explain what this is, I should probably first explain something about Factor identifiers.

A valid Factor identifier is any string which matches the following:

^[^"][^s]+$

Yes, that's it. Any identifier can contain any character that isn't whitespace, and it can't begin with one or more "s, because strings are special to the lexer. It can have " elsewhere within it, though.

The NUL byte, the character at UTF8 888 and the byte at 127, ASCII DEL are all valid identifiers. For portability, sometimes SYMBOLs may be stripped of their non-ASCII bytes (Windows, for instance).

This may be rather shocking to the C people and the Python people (and even the Lisp people, who allow some nice stuff in names), but fear not, for you will come to like it.

So 2bi@ is just one identifier, one name for one function. But what does it do? Well, the bi@ function applies one quotation to two items on the stack:

"5" "10" [ string>number ] bi@

--- Data stack:
5 
10

(bi stands for bifurcate, if you were curious.)

"5" "10" "15" "20" [ append string>number ] 2bi@

--- Data stack:
510
1520

2bi@, like 2map, takes a quotation with stack effect ( obj1 obj2 -- ... ), which gets applied first to w and x, then y and z in pairs.

Length 5

Finally, a word for working with sequences. Factor is no APL / J / K / Octave / what have you, but its array processing skills are... close... kinda.

union

If you're familar with Python (like I am), then you may recognise this better as the | operator on sets:

{ 1 2 3 } { 2 3 4 } union

--- Data stack:
{ 1 2 3 4 }

Removes duplicates while performing element-wise OR. Technically, the union word is from the sets vocabulary and not the sequences vocab. This is because, like Python, sets are special, super-fast immutable sequences that don't allow duplicate entries.

Also much like Python, any sequence (byte vector, hashtable, set, etc) that implements the Sequence protocol (__iter__ being the equivalent in Python) is considered fair game and supports a well-defined set (hah) of operations, so any word that works on a generic sequence A will also work on a generic set B if both have the right method dispatch.

Length 6

Ooh, more arrays! (Note that arrays are immutable; all operations on them yield new arrays and the old ones are GC'd. Vectors are mutable and slower, but we'll cross that bridge when we get there.)

2array

This is a highly useful word. Any guess at what it does? Here:

IN: scratchpad 1 2 2array

--- Data stack:
{ 1 2 } 

IN: scratchpad { 3 4 } 2array

--- Data stack:
{ { 1 2 } { 3 4 } }

Well shucks, it takes two things off the stack and makes a new array from them. 1array, 3array and 4array all do exactly what you'd expect, and narray takes an arbitrary n argument, to avoid messy concatenation code.

If I may digress yet again about naming...

In Java or Python, one might call this function values2array or valuesToArray or even values2Array. However, here in Factor-land, we have some conventions.

Remember my spiel about identifiers? Numeric digits in names should only be used for indicating real numbers or counts of things; in particular, this means 2array should not be read as to-array but as two-array.

The word which does to-array is called >array. The word which turns a number to a string is number>string, and the word which turns an object's slots to an array is tuple>array. See a pattern? Hmm.

Users of Racket will feel right at home with these sorts of names, since Racket uses stuff like number->string.

Answered by cat on November 19, 2021

05AB1E

Length 7 snippet:

Code [Try it online!]:

”Ÿ™,‚ï!

This is using a dictionary compression method. This will result into Hello, World!. Every ASCII character is interpreted as a normal character and every character with a code point above 127 is used for the decompression itself:

”       # Start a compressed string with all words titlecased
 Ÿ      # In Info.txt, you can see that this has index 24
  ™     # Index 19
        # These two indexes combined is 2419, in the dictionary you can see that the
          2419th word is hello
   ,    # Since this has no index, this will be interpreted as a normal character
    ‚ï  # Index 0118, which is the word "world". An extra space before this word is
        # implicitly added.
      ! # Regular exclamation mark
        # All the compressed words are automatically title cased.
          resulting in: "Hello, World!"

Length 6 snippet:

Code [Try it online!]

D=gGÁ=

This creates a square with a rotating string. For example, the input Hello would result into:

Hello
oHell
loHel
lloHe
elloH

The input is first Duplicated, then printed with a newline without popping (using =). We take the length of the string, and create a for loop with G and each time we rotate the string 1 to the right using Á and print it again without popping. This is done length - 1 times, so in total this is done in length times.

Length 5 snippet:

Code [Try it online!]:

žnžo‡

This does the Atbash cipher. The ž command contains all kind of shortcuts to constants. Right now, the list of constants is:

ž 23  > ža           push current hours
        žb           push current minutes
        žc           push current seconds
        žd           push current microseconds
        že           push current day
        žf           push current month
        žg           push current year
        žh           push [0-9]
        ži           push [a-zA-Z]
        žj           push [a-zA-Z0-9_]
        žk           push [z-aZ-A]
        žl           push [z-aZ-A9-0_]
        žm           push [9-0]
        žn           push [A-Za-z]
        žo           push [Z-Az-a]
        žp           push [Z-A]

So, we can conclude that žn is equal to [A-Za-z] and žo is equal to [Z-Az-a]. After this, we just perform a transliteration using .

Length 4 snippet:

Code [Try it online!]:

Œvy,

This is maybe not a very tricky one, but certainly interesting. The Œ command computes all substring that can be made with the string. Then, we map over the array containing all the substrings using v. y is the variable which holds the string and , prints that with a newline.

Length 3 snippet:

Code [Try it online!]:

³¹²

This is using a pretty neat feature of 05AB1E. What this does is pushing the third input, then the first and then the second. You can see this best with the debug mode on.

Length 2 snippet:

Code [Try it online!]:

LO

This calculates (n × (n - 1)) / 2, which is also the formula for triangular numbers. What this does it make a List in the range [1 .. input] and then calculates the sum using O.

Length 1 snippet:

Code [Try it online!]:

!

Well, this isn't particularly interesting except the fact that input is implicit. When the length of the stack is smaller than the arity of a function, input is used instead. This just calculates the factorial of the input.

Factoid

05AB1E is a language I, (Adnan), have made. It can be pronounced in several ways, like Osabie, Osable, Zero-five A B one E. They are all correct since there is no actual way to pronounce the language. The name itself has a deeper meaning. When interpreted as a hexadecimal number, converting this number to Base64 would result into: Base.

Answered by Adnan on November 19, 2021

LiveScript

Factoid: LiveScript was on of the early names of JavaScript (mocha is another one), before the need to "make it feel entreprise-y" came up. The language offers features that spans in different paradigms (mostly functional and object-oriented).

1 vote

@

This is simply a shortcut for "this", or property access into "this".

2 votes

->

We can define a function! Albeit empty for now.

3 votes

(+)

The language allows you to use binary operators as functions. They're also curried!

4 votes

v|>f

The pipe is, like in F#, a "reversed" function application: the above is equivalent to f(v).

As a bonus, the opposite operator also exists: (like $ in Haskell)

f<|v

which is equivalent to f(v) (this is useful for precedence).

(of the two, <| has lowest precedence).

5 votes

class

Yes, this actually works as a standalone anonymous classes. They're values, and very powerful – they have executable bodies (a bit like Ruby). This allows to declare method on-the-fly, but that's going to be a bit later :).

6 votes

"#{3}"

String interpolation! It's particularly powerful in LiveScript, where there's even a shortcut for interpolation variables – the braces aren't needed: "#x"

7 votes

->|_=>1

This is a bit useless as-is... but in LiveScript, switches are implicit right after a function declaration (->), and a case can also be spelled | (ML-style). The => is an alias for then (but doesn't require spaces around it), and _ is a catch-all.

This is basically the sugar-y syntax for (a topic-less switch will switch on truthiness):

->
 switch
 # case ...
 otherwise
   1

8 votes

@a{}b[]c

@a is simply @.a, which is... this.a! The language inserts dot for you in my places.

In LiveScript, [] and {} used as infix operators (they're actually infix dot operators, the real spelling is .{} and .[], but those dots can be inferred) are (semi)autovivification (like in Perl)/shaping member access.

(contrarily to perl, you need to use {} and [], hence the semiautovivification)

It means a{}b (or a.{}b) tries to access a.b, but if that key doesn't exist (or is == null), it creates it as an empty object ({}). For a[]b, it does the same, but initializes an empty array ([]) instead.

The postfix ! is actually simply (), an argumentless call. Here again, the language will insert dot as needed:

a!b
a()b
# both mean
a().b
# and equally...
a()['b']

Answered by Ven on November 19, 2021

ForceLang

ForceLang (name proposed by TanMath) is a programming language I published on January 12.

Functionality includes arbitrary-precision rational numbers, both console and GUI IO, and file input (file output has not yet been added, but will likely be added later)

Control flow is currently handled using gotoes, evaluated gotoes, and conditionals.

Length 1 snippet: 0

A number literal for the rational number 0/1.

Length 2 snippet: io

The io namespace contains the language's console and file IO functionality. GUI IO is located in a separate namespace.

Length 3 snippet: nil

A constant field containing the null reference.

Length 4 snippet: 0xFF

A hexadecimal number literal for the rational number 255/1 (hexadecimal literals can only be used for integers).

Hex literals are useful as color codes for the language's (currently somewhat limited) graphics library.

Length 5 snippet: 11/13

A number literal for the rational number 11/13, which is stored exactly as a BigRational.

Length 6 snippet: !!TRUE

Obviously, this returns TRUE.

Length 7 snippet: def a a

An abuse of the def instruction that causes any subsequent attempts to evaluate the expression a to result in an infinite loop.

Length 8 snippet: gui.show

A method that produces a simple gui alert.

Length 9 snippet: math.sqrt

Estimates the square root of a number as another BigRational. It does this by doing some math to find an integer which approximates this value, then applying four iterations of the Babylonian Method to this initial approximation.

Length 11 snippet: random.rand

The function random.rand can be used to produce random numbers on [0, (2^m-1)/(2^m)] for arbitrary positive integer values of m (effectively on [0,1) as m becomes large). When called with no arguments (random.rand()) it uses m=80.


Some other answers in this language:

Answered by SuperJedi224 on November 19, 2021

Jolf

0-vote

Factoid: Jolf is my personal utility language, and is sometimes suited for golfing; it was created mainly out of frustration trying to learn Pyth.

1-vote

τ

Jolf is encoded in ISO-8859-7, the Greek encoding. Not only is this one character, but it is also one byte. This stands for 2*pi, or the literal constant tau. Try it here!

2-vote

~ (there is a trailing space)

The tilde is one of the many extender functions in Jolf that allow for 2-byte sequences of characters. In this case, ~ is the ISO-8859-7 encoding. Try it here!

3-vote

ͺπt

This simply reads "pair pi and ten"; ͺ being the function that wraps two elements in an array, π being pi, and t being ten. (Also, Jolf has implicit output and that's good for stuff.) Try it here!

4-vote

Ξhi!

Jolf is hostile. It does not like being talked to. Therefore, it says "ATTACKING " when prompted. Just kidding, this is actually Jolf's string compression in action. In this case. it's using it's dictionary. Try it here!

5-vote

»HΒM!

This is Jolf's string compression in action. This output's the string "Hello!". Jolf uses shoco for compression/decompression. Try it here!

6-vote

ΣdQH1j

This is the first complex program here! Σ is function summation that accepts a function, a minimum, and a maximum. In this case, the function is dQH. d begins a single-arity function with arguments H, S, and n. H is the only argument we are concerned with for the moment. In this case, it is the number being acted upon. QH squares H, and j is the input. So, from 1 to the input, we count the sum of the squares. (If we were golfing, we could move the square function into a lambda as this: ΣλQ1j.) Try it here!

7-vote

mΦx0/9t

This is another one of Jolf's builtins: Fibonacci with custom seeds. In this case, we take input (x) and perform the Fibonacci sequence with Φ(0) = 0 and Φ(1) = 9/10, and that Φ(n+2) = Φ(n+1) + Φ(n). Try it here!, or see the first 16 results in the sequence.

8-vote

₯S₯C+'0q

This is a sort of "growing" quine. is the document package, and this is what it looks like explained:

₯S₯C+'0q
₯S        set the value of
  ₯C      the code
    +'0   to "0" +
       q  the source code

Try it here!

9-vote

U+ΏQm4HXΏ

This is the distance formula for two array inputs! Ώ defines a function Ώ which can later be used.

U+ΏQm4HXΏ
   Qm4H    square the asum of H (e.g. if H = [a,b] m4H = a-b)
  Ώ        a function Ώ does this
       X   initially called with eval'd input
 +      Ώ  added to Ώ(x) (implicit input)
U          square root

10-vote

ΜzάdySHHHH

Try this one here!

I'm calling this the "be quiet, jrich!" program. It outputs this, using Jolf's turtle:

jrich is quiet

This looks a lot like jrich's avatar. This is how it works:

ΜzάdySHHHH
Μzάd        map 1 .. 16 over this function
    yS      create a square
      HH    at (H, H)  ; the index
        HH  of dimensions H x H

11-vote

"Hello, %!"

This greats the user, using string interpolation (%) and implicit input.

Try it here!

12-vote

ps"afaik:lol

This outputs as far as i know:laughing out loud. Apparently, Jolf likes to text. Oh well.

13-vote

~jd=ΏmΓChHHΏS

This takes input (implicitly). It finds all pairs of integers below the input x that satisfy the condition of being before a number having the same collatz sequence length. Explanation:

~jd=ΏmΓChHHΏS
~jd            all pairs satisfying condition (think "~jenerate")
    ΏmΓChH     define a function Ώ that heads H and finds its collatz sequence length
          H    call Ώ on H (outer H)
   =       ΏS  call Ώ on S and see if its = to (^)

This is a demonstration of the concept, rather than a helpful one. Here's one that gives more clear results and filters self equal arrays:

ψh~jd=ΏmΓChHHΏSxd~!=FHgH

Can be golfed, but eh.

Answered by Conor O'Brien on November 19, 2021

Wierd

Factoid

Unlike other languages where the symbols in a program determine which instructions are executed, in Wierd, it is the bends in the chain of arbitrary symbols that determine which instructions are executed.

Chris Pressey created the angle-to-instruction mapping, and christened the entire mess "Wierd"--a cross between the words "weird" (which the language seemed to be) and "wired" (which would describe the appearance of programs written in the language)

You can try it online at http://catseye.tc/installation/Wierd_(John_Colagioia)

Length 1 Snippet

!

The actual character used doesn't matter - it can be any non whitespace character. This program doesn't do anything because there are no bends in the chain of characters - but there is a chain so at least it is a valid program.

Length 2 Snippet

++

Now we are going somewhere - we have a chain of characters. Still no bends so you wouldn't expect it to do anything but unintuitively this program does actually do something.

The current location starts in the top left corner facing "diagonally down and right". The current location always moves with inertia - it will move in the direction it is already moving until it can no longer do that and then will move in a direction closest to the current direction.

So the current location has to change 45 degrees so that it can continue to the right and that counts as a 45 degree bend so we push 1 onto the stack - exactly the same outcome as the Length 5 Snippet.

Length 3 Snippet

+
+

Same as the Length 2 Snippet this program does actually do something because the current location starts in the top left corner facing "diagonally down and right" and the current location has to change 315 degrees so that it can continue to the right and that counts as a 315 degree bend which will subtract the two items on the top of the stack. But there is nothing on the stack so the bend is a no-op and the program does nothing.

Length 4 Snippet

+
 +

The current location starts in the top left corner facing "diagonally down and right" so there are no bends in this chain of characters and so this program doesn't do anything.

Length 4 Snippet

+
++

Finally a program with a bend! But it doesn't do anything useful :(

The current location starts in the top left corner facing "diagonally down and right". The current location always moves with inertia - it will move in the direction it is already moving until it can no longer do that and then will move in a direction closest to the current direction.

So the current location moves "diagonally down and right" and arrives at the next bend. It is a 225 degree bend so if the stack were to contain a zero it would push one character of standard input onto the stack and if it were a nonzero value then a value from the stack would be written to standard output. But there is nothing on the stack so the bend is a no-op.

Now the current location moves around the bend without doing anything, the current direction is towards the left and we are at another bend. This one is a 270 degree bend so if the stack were to contain a nonzero value the current direction would reverse. But there is nothing on the stack so the bend is a no-op.

Now the current location moves around the bend without doing anything, the current direction is up and we are at another bend. It is a 270 degree bend so if the stack were to contain a nonzero value the current direction would reverse. But there is nothing on the stack so the bend is a no-op.

Now the current location moves around the bend without doing anything, and we are in an infinite loop.

Length 5 Snippet

+
 ++

Finally a program that does something!

The current location starts in the top left corner facing "diagonally down and right" so the current location moves "diagonally down and right" and arrives at the next bend. It is a 45 degree bend so we push 1 onto the stack.

There are only four ways to get values onto the stack:

  • Push a 1
  • Subtract two values already on the stack
  • Use a value on the stack to decide to read from standard input
  • Use corordinates on the stack to read a value embedded in the program

So the only way to get a value onto an empty stack is to push a 1.

Answered by Jerry Jeremiah on November 19, 2021

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.

Answered by M L on November 19, 2021

haxe

Haxe is a neat language that lets you target a lot of major platforms with the same codebase - desktop, mobile, web, server, anything.

Finding good examples for the first couple of votes will be hard, so bear with me :)

1

.

Dot is the operator to access class fields and methods, object properties, or enum properties.

2

[]

This is an empty array. More on arrays (array comprehension) later.

3

3*9

Multiplication. The compiler is smart enough to change that into 27 in the resulting code, even in less strict languages (e.g. JS).

5

0...9

This is a shortcut to create an IntIterator, which will produce the numbers 0 to 8 (inclusive).

for (i in 42...45) Sys.println(i);

Produces

42
43
44

Answered by Aurel Bílý on November 19, 2021

GoLScript

Interpreter.

5-vote

HAAZW

This is another simple program.

Generation 0

H pushes 7, A pushes 0. Z is a fun command that pops Y, X and pushes the character at FIELD[Y][X], or (X,Y). In this case, the character at (0,0) is H, and so it's char code is pushed. W outputs this as a character.

The two outer-most cells die.

Generation 1

We are left with AAZ, another call to Z, pushing h's char code to the stack (as the former H is now dead and thus lowercase). However, since the W died, it can no longer function, and thus, this phase ends.

Once again, the two outermost cells die.

Generation 2

Now, only A is left, which carries out its duty in pushing a 0, and then dies. The program is effectively stopped.

4-vote

Bp
P

(newline counts as a character, iirc.) This does something rather simple:

  1. The program is first BpP. This pushes 1 (B), pops a value (1) and assumes it p => P, and does that again, popping a zero from the bottom of the stack P => p.
    1. Checking, only the new P survives, as it popped a value and lived. The rest of the characters died.
  2. After, only the P remains; it pops an empty value (0) and dies.

3-vote

JXJ

First multi-step program! Here's what happens:

Generation 0

The code is evaluated: J pushes 9 to the stack, X pops a number and prints it, and J again pushes 9 ot the stack.

The cells' live-states are updated. Both Js die, having only 1 neighbour. The X lives, as it has 2 neighbours.

Generation 1

All that remains is the X. This prints the remaining 9 off the stack.

The X dies, and the program terminates.

Final output

99

Hey, it's a start…

2-vote

@V

The shortest (?) still life in GoLScript. @ negates the top of the stack (effectively pushing true) and V reads the top of the stack, and dies if the value is falsey. Replacing @ with any of B-J would also produce a still life.

1-vote

X

Any 1-length program is valid. This one takes a zero of the stack (there is an infinite amount of zeroes atop the stack) and outputs it as a number.

0-vote (factoid)

GoLScript simulates Conway's Game of Life! Yay! Interpreter. You'll have to copy-paste the codes, and output is the bottom-most code block.


Language information

  • GoLScript is stack-based.
  • GoLScript has no native string quoting!

Answered by Conor O'Brien on November 19, 2021

Golfical

Golfical is a shiny, brand-new graphical programming language I made over the past few days, and published earlier today.

It uses a stack, a tape, and a register as memory. But primarily the tape.

The included encoder utility can be used to compress programs into a raw binary form, which can then be converted back to the original image or run directly by adding the -x flag. This requires from one to three bytes for each pixel, plus three bytes extra for encoding the dimensions (length and width are encoded as twelve bits each, just in case 8 isn't enough for some reason.)

Of course, the encoding is somewhat lossy, as all other colors that don't have instructions assigned to them are changed to white (both to save space and because the specs guarantee that no instruction will ever be assigned to white.)

One pixel example:

enter image description here

Magnified 200x, with color labels:

enter image description here

When the red channel is zero, Golfical interprets the green and blue channels as an integer literal and stores it in the target of the pointer. Thus, this stores the value 255*256+255=65535 into the target of the pointer. This is the largest number that can be stored directly in this way, though cells can be set in longer ways to values as large as 231-1.

In the binary encoding generated by the included Encoder utility, this would represented by three bytes; the encoding includes an optimization that allows only two bytes to be used for this instruction when the green channel is zero.

Two pixel example:

enter image description here

Magnified 160x with color labels:

enter image description here

(10,0,0) inputs a number and (10,1,1) outputs it as a character. In the compressed binary encoding, these two instructions add one byte each.

Three pixel example:

enter image description here

Magnified 160x, with color labels:

enter image description here

(10,0,1) is like (10,0,0), except it reads a character instead of a number. (12,0,0) pushes the target of the pointer to the stack. (The binary encoding represents these instructions as 1 byte each.)

Therefore, this snippet reads a character, pushes it to the stack, and then reads another character.

Four pixel example:

enter image description here

Magnified 125x, with color labels:

enter image description here

Simulates the rolling of a d100. The two new instructions here are 02xxxx (which works like 00xxxx but as an increment instead of an assignment) and 0D0001 (13,0,1) which sets the target of the pointer to a random integer between 0, inclusive, and its previous value, exclusive. Like 00xxxx, 02xxxx is represented in the encoding using two bytes if the green channel is zero or three otherwise. 0D0001 is represented as one byte.

Five pixel example:

It took me a while to decide what to do with this one, but eventually I decided to go with this:

enter image description here

Magnified 125x, with color labels:

enter image description here

(11,0,0) through (11,0,3) are absolute turn instructions (relative turn instructions, as well as many of the conditional relative turns, are later in the 11 block). (11,0,1) is East and (11,0,3) is West.

This program prints lolololololololololololololololololo ad infininum.

Six Pixel Example

enter image description here

Magnified 200x, with color labels:

enter image description here

An infinite counter (limited, of course, by the 32-bit two's complement integer range; a proper infinite counter would be much harder to implement.) Also our first properly 2-dimensional example here.

Eight pixel example:

Magnified 100x with color labels:

A primality tester using the language's prime testing builtin (14,3,0), which makes a relative right turn if and only if the target of the pointer is prime. The official encoder program encodes this program in 13 bytes.

Answered by SuperJedi224 on November 19, 2021

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.

Answered by Adnan on November 19, 2021

PowerShell

Length 15 Snippet

(1,0,'E')[$x%2]

It is a very short way to output truthy/falsey values if you are asked to determine if $x is even. (or E for error)

It golfs down a switch statement

switch($x%2){0{1}1{0}2{'E'}}

It can index the array using modulo. So the basic algorithm is:

  • If $x is even, then $x%2 is 0, so first element in array is 1
  • If $x is odd, then $x%2 is 1, so first element in array is 0
  • Otherwise if $x%2 errors, it shows E

Same trick can be applied to output 1 (Truthy value) for odd number.


Length 14 Snippet

$a|% t*y|%{$_}

This combines several snippets below into a very powerful feature. Still using % as an alias for foreach-object, we use both of its position-0 positional parameters: -memberName which takes a string and will return the specified member for each object and can take wildcards provided they resolve to a non-ambiguous name (String's toCharArray in this example); and -process which applies a script-block to each object ({$_} in the example).

The example above is a way to iterate through each character in a string and implicitly output it.


Length 13 Snippet

1,1|select -u

Parameters in PowerShell can both be positional and expanded. Positional meaning if the parameter flag isn't explicitly specified, it can be inferred. For example, Get-Random 10 is the same as Get-Random -Maximum 10, because the -Maximum parameter is positional.

Here, we're using the expandable property of parameters. Since -Unique is the only parameter to Select-Object that starts with -u, we don't need to spell out the entirety of the parameter. Both of these features saves tons of bytes.

The output of this snippet, which feeds an [int]-array into the Select-Object cmdlet is 1, as an [int].


Length 12 Snippet

0xff*2KB-2e6

PowerShell has some weird special operators that allow large numbers to be written in small number of characters.

The 0x unary operator converts characters from hexadecimal to decimal. For example, 0xff --> 255 or 0xbeef --> 48879.

The KB (and MB, GB, TB, and 'PB') unary operators take input on the left and multiply it by 1024, 1048576, 1073741824, 1099511627776, or 1125899906842624, respectively. For example, instead of [int]::MaxValue, or 2147483647, you can write 2GB-1.

The e (exponentiation) binary operator basically takes the input on the left and tacks on (the input on the right) number of zeros. For example, 2e6 --> 2000000.

The output of this snippet as written is -1477760.


Length 11 Snippet

$a=($b=1)+1

In PowerShell, it's very important to remember that you're dealing with objects on a pipeline. This can be manipulated in several ways, and the above shows the concept of encapsulation. Commands placed in parentheses are executed first (as you'd expect), but the output of the command is left on the pipeline to be picked up later. Here, we're assigning $b to be 1, and then assigning $a to be $b+1. This snippet is equivalent to $b=1;$a=$b+1, and shows an easy way to golf bytes anytime you're doing an assignment.

The implications here go beyond just that, however, since it's the PowerShell pipeline and so we're dealing with objects. This means that complex object creations can have nested function or procedure calls, for example calling a constructor and immediately calling a method on the resultant object, and then immediately calling a property on the result. Something like (((New-Object foo).bar()).GetBaz()).baz is perfectly legitimate. In some cases, you don't even need to assign the object to a variable.

Additionally, since anything left on the pipeline is implicitly printed after execution, this means you can accumulate data on the pipeline and print for essentially free. For an easy example, a simple accumulator from 1 to 10 (prints 1, then 3, then 6 ...) can be 1..10|%{($a+=$_)} vs 1..10|%{$a+=$_;$a}, saving a byte, but can save significantly more in other situations. Since we're talking about output, this is a good time to bring up that nearly every output to the console/shell in PowerShell includes a newline (technically rn because it's Windows), so if the challenge requires separators we get that for free, too.


Length 10 Snippet

$a,$b=1..9

PowerShell has the capability to do multiple assignment. In the above snippet, $a will be 1, an int, while $b will be (2,3,4,5,6,7,8,9), an int-array. This has the ability to save lots of bytes if you're looking for particular items -- for example, $a,$b=-split$somestring will split $somestring on whitespace, store the first word in $a and the rest in $b. Very useful if you're looping through a string, for example, or re-manipulating the rest of the string in some fashion.


Length 9 Snippet

(4,9)[$a]

PowerShell has very loose type casting. Very loose. We can thus abuse this typecasting to transform array-indexing (as the above) into an if/else statement. For this snippet, if $a will somehow evaluate to a truthy value (a non-zero number, a non-empty string, any other non-$null variable, etc.), the Boolean result will be typecast to a 1 and so the 9 will be selected. Conversely, if $a evaluates falsey, the 4 will be selected. This is PowerShell's x?y:z style ternary if, and is significantly shorter than the equivalent if($a){9}else{4}. It's rare for an actual if/else statement to show up in PowerShell golfing.


Length 8 Snippet

$c+=++$i

A simple example showing a couple basic operations. PowerShell has both pre- and post- increment and decrement operators (++ and --), and they function pretty much like you'd expect, except when it comes to uninitialized variables. Running the above snippet in a brand-new shell will result in ++$i evaluating first as $null + 1 = 1 and storing in $i, then adding that result to $c (also $null), which makes $c equal to 1 as well. Flip the pre-increment to be a post-increment and you get a different result, with $c = 0 and $i = 1, but with $c cast as an Int32. This null-arithmetic is a sneaky way of shaving a couple bytes here or there, especially when it comes to not needing to check if a variable already is initialized.


Length 7 Snippet

,'a'*$b

Yeah, so that's a thing. No, really. It's the PowerShell comma operator and it's used to create arrays. As an inline (binary) operator, it creates multi-element arrays, as in $myArray = 1,2,3. As a unary operator, it creates an array with one member, as in $myArray = ,1. In both instances $myArray.GetType() will tell us that it's a System.Array object. Here, we're coupling this with operator overloading (multiplication, specifically) to create an array of length $b with each element equal to 'a' -- that is, we can create and pre-populate an array in one go. It's important to note that the array element is evaluated once and then multiplied, so you can't do something fancy like $a=1;$b=5;,($a++)*$b and expect an array 1,2,3,4,5. Bummer.


Length 6 Snippet

$a-gt2

OK, pretty simplistic, but this is a continuation of the below concepts. In addition to the usual +-*/ operator overloading, PowerShell comparison operators (-le -eq -gt etc.) are overloaded, too. As are most other "basic" operators.

Let's suppose that $a=3, an int. Then, the above snippet will result in $TRUE as it's comparing "is 3 greater than 2?" So far, so standard. However, let's take $a=(0,1,2,3,4,5) an array of int's from 0 to 5. In this case, the above snippet will result in an array (3,4,5) - that is, it constructed a new array and populated it with all elements of $a that are individually greater than 2. Have a constructed array already and want to know how many elements are equal to 0? Try ($a-eq0).Count. Want the biggest element in the array that's smaller than a certain value? How about ($a-lt4|sort)[-1] (using our "last element" trick from Snippet 4).

This sort of operator overloading continues to other objects, too, not just arrays and ints. $StringA -gt $StringB will categorize the two strings alphabetically. $CharA -gt $CharB calculates based on their ASCII value. And on and on and on. Pretty much any object in PowerShell can be compared like this.

As a bonus, in most cases, if the right-hand operand can be parsed appropriately, you can mix and match types like you can with normal arithmetic operators. As an example, $DateA -lt "2015/12/17" will implicitly parse the right-hand string into a .NET datetime object to calculate comparison.

Combined, the Length 5 and Length 6 snippets allow PowerShell codegolf answers to be very loose with type-casting, which cuts out a tremendous amount of bytes.


Length 5 Snippet

$a+$b

"What, really? The plus-sign is what you're showcasing? Phaw!" OK, OK, put down your torches and pitchforks, and hear me out. I'm showcasing operator overloading. "Well, so what, plenty of other languages have that! Plus, you showed that for your Length-1 Snippet!" Yeah, but that needs to also be coupled with PowerShell's powerful implicit casting and implicit parsing.

Operations like the above snippet in PowerShell take on the characteristics of the left-hand side operand. Suppose $a='123' and $b=4, with the first as a string and the second as an int. With the above snippet, the result will be 1234 as a string. Flip the order $b+$a and PowerShell will implicitly parse the string object to turn it into an int, and the result will be 127 as an int.

While this is powerful, and allows you to abuse plenty of different operators for nefarious codegolf purposes, it has the quirk feature that operators are not commutative. In other words, ($a+$b) -eq ($b+$a) will return False in lots of cases.


Length 4 Snippet

[-1]

A secret weapon used when indexing arrays or strings or the like to retrieve "the last element." We don't even need to know the length of the array. Want the second-to-last element? Use [-2] instead. And so on.

One example where this comes in handy is in finding the maximal of a list of numbers. Suppose we previously stored them in $x. PowerShell already has an alias for Sort-Object as sort, thus, we can do ($x|sort)[-1] to pull out the maximal item from $x, and we don't even care or know how many items are in $x, and it's significantly shorter than the "regular" method of ($x|measure -maximum).Maximum.


Length 3 Snippet

iex

The command iex is an alias for Invoke-Expresssion, and is similar to an eval() style statement. However, it has implications for codegolf in that it can take parameters or pipeline input (because remember, the pipeline hands off objects, not text).

As a simple example, suppose I need to sum the numbers from 1 to 10. I could write 1+2+3+4+5+6+7+8+9+10, but at 20 bytes that's pretty lengthy. I know I can get a range of numbers using the .. range operator, such as 1..10, but now I essentially have an array of integers. I can concatenate them together with the join operator, like so 1..10-join'+', and now I have a string that can be fed into iex as 1..10-join'+'|iex, for 17 bytes. This simple example shows how very complex commands can be dynamically constructed rather than hardcoded, but still be executed as if they were coded directly, and can significantly cut down on byte-count.


Length 2 Snippet

$_

This was already introduced below in the Length-1 snippet, but it's important enough to reiterate here. Another strong suit that gives PowerShell advantages in codegolfing is the concept of automatic variables. That is, variables that are implicitly created in the background by the system. Here, the $_ variable stands for "the current object in the pipeline." Essentially, it's a variable that is a dynamic placeholder for whatever object we're currently manipulating.

In the example loop 1..1e4|%{$_%5}, the $_ variable first holds the integer 1, then 2, then 3, etc. The power is more evident when dealing with a collection of different objects - $_ could be a string, an int, a custom PSObject holding the entire Windows System Event Log, a TCP/IP socket object, etc., all dynamically typed as the situation changes.


Length 1 Snippet

%

The other answer used a pipe | for the Length-1 snippet, and that's probably the most important 1-symbol snippet for 99% of use cases, but the % is functionally way more powerful for codegolf purposes, and introduces two important concepts.

The first is one of PowerShell's hidden codegolf weapons, aliasing, which significantly cuts down code length. Here, the % character is a standard alias for ForEach-Object, and allows us to create loops with very little code overhead.

The second is operator overloading. In PowerShell, as in other languages, the % operator stands for modulo -- 3%2 will return 1 as an example. However, thanks to a strongly/weakly typed system (more on that later), and strong syntax requirements, the same character serves double-duty.

For example, 1..1e4|%{$_%5} is a loop that will generate and output a 123401234012340... string that's 10,000 characters long (with newlines in between, more on that later).

I've already rambled at length about the differences between ForEach and ForEach-Object, so I won't redo that here.


Factoid

Windows PowerShell had its origins over a dozen years ago (and actually just had its 9-year release anniversary; the original release was 14/Nov/2006) as Monad and the Microsoft Shell. I highly recommend reading the Monad Manifesto, originally published in August of 2002, for an amazing insight into the development process and reasoning behind naming conventions and features that developed to make PowerShell what it is today.

Bonus Factoid -- Even from the very beginning, there was pushback from hardcore users regarding the name change from Monad to PowerShell, including some pundits calling it a fad that would never catch on.

Answered by AdmBorkBork on November 19, 2021

Whitespace

Factoid:
It allows Whitespace programs to be hidden in the source code of programs in languages like C.

Length 1

[LF]

A single line feed. This is an Instruction Modification Parameter (IMP), which is the first token to determine which category of commands the code will be executing from. Line Feed corresponds to Flow Control.

Length 2

[space][space]

The [space] IMP corresponds to Stack Manipulation. Two spaces inserts the rest of the line of spaces and tabs encoded as binary onto the stack.

Length 3

[LF][LF][LF]

Once again, [LF] corresponds to Flow Control. Three line feeds in a row terminates the program.

Length 4

[tab][LF][space][space]

[tab][LF] corresponds to I/O. This command outputs the character corresponding to the value at the top of the stack.

Length 5

[space][space][space][tab][LF]

Pushes the number 1 onto the stack. This is an example of how numbers are defined for commands such as the Length 2 snippet: the first bit is the sign bit, with [space] being positive and [tab] negative, then for the rest of the line, [space] is 0 and [tab] is 1.

Length 6

[LF][space][space][tab][tab][LF]

[LF][space][space] is a command to mark a label for jumping/subroutines later, and the rest of the line is encoded as binary as mentioned above. This one defines the label -1.

Length 7

[LF][tab][space][space][tab][space][LF]

[LF][tab][space] is jump-if-zero. This snippet jumps to label 2 if the top of the stack is 0.

Length 8

[tab][LF][tab][tab][tab][LF][space][space]

Let's write some meaningful programs now! This executes a command to read a number from STDIN and print the corresponding ASCII character.

Length 9

[space][space][tab][tab][LF][space][space][LF][space]

[space][space][LF][space] is a command to duplicate the top item on the stack, so this will push the number -1 onto the stack, then duplicate it.

Length 10

[space][space][space][tab][space][LF][tab][LF][space][tab]

Pushes 2 onto the stack, then prints it.

Answered by Minzkraut on November 19, 2021

Mouse-2002


Length 6

&GMSUN

Pushes on the stack 1.32712438E+20 (in scientific notation!), or the gravitational mass of the sun.2

Length 5

&SWAP

Swaps the top two things on the stack. Concisely, ( x y -- y x ). Again, not that interesting; most mouse programs have to be somewhat longer to be interesting.

Length 4

&DUP

Duplicates the thing on the top of the stack. That is, makes a copy, and pushes that copy. Unfortunately expensive in terms of bytes. I think it was not the first thing on Simpson's list of easy-to-access functions.

Not particularly interesting.

If you've ever seen or written False (or, for that matter, False!) or, indeed, Forth, you'll notice a lot of Mouse is shockingly similar. I love Forth, and my guess is False's creator had perhaps heard of Mouse (because Mouse far predates False, but is predated by Forth by 9 years).

Length 3

&AU

Pushes "the value of one astronomical unit of distance"1 to the stack. The guy who reimplemented and updated this language had a hand on programming spaceships at NASA for the Apollo missions, so it figures he'd include a whole bunch of physics and maths related constants.

My reboot of the language will also contain these constants, because they're cool.

Length 2

A:

Takes the thing on the top of the stack and puts it in A. e.g, 1A: puts 1 into A, and 3 5/A: puts 3/5 into A. (oh yeah, Mouse uses Reverse-Polish-Notation!)

Length 1

?

Prompts for a number to be input, and puts it on the stack.

Factoid:

Mouse-2002 is an updated reimplementation of Mouse-83 by David Simpson. Mouse-83 was described in the book Mouse: A Language for Microcomputers by Peter Grogono. It includes a number of enhancements over the earlier version, Mouse-79, which was described in an article by Grogono in Byte magazine in July 1979.

Mouse is a rather ancient, yet turing-complete stack based language, which, while no instruction uses more than a byte, is still likely less golfy than CJam or Pyth.

Fixed interpreter here.

I'm planning to update it and reboot it with even more concise syntax and better features; no interpreter yet, though. It will be almost as golfy as CJam (though that isn't the main intent) while being far more readable and usable outside codegolf.

Answered by cat on November 19, 2021

LabVIEW

LabVIEW is a graphical programming language mainly used for measurement technology.

Factoid:

LabVIEW used to store Bools in 2 Bytes

Note: since LabVIEW is strictly graphical the sizes are in Labview Primitives

Lenght 1 Snippet

LabVIEW is used in 2 windows, the left one (Block Diagramm) where the programming happens and the right one (Front Panel) for in and output. Putting a control on the Block Diagramm automatically puts the input on the Front Panel

Lenght 2 Snippet

there is actually no working programm of size 2 apart from just putting 2 controls or constants, so ill add another fact.

LabVIEW works exceptionally well with Arrays. They can be automatically indexed when put into a for loop and you can easily use basic arithmetic and binary operations on arrays and numerics of different dimensions.

Lenght 3 Snippet

I just realized i could use express VIs but that feels like cheating. They are basically full written out programms that get compressed into 1 VI. I might put one in if anyone wants to see it, so leave a comment.

Lenght 5 Snippet

This is one of the array operations one can do.

Lenght 6 Snippet

Another fact:

The size of a full LabVIEW installation can be well over 20 GB.

Answered by Eumel on November 19, 2021

Japt

Japt is a shortened version of JavaScript, created by myself in early November 2015.

Click on any snippet's header to try it in the online interpreter!

Factoid

Japt is heavily based off of JavaScript. After transpiling Japt's syntax features to JS, it is evaluated as vanilla JS. This allows easy building of an online interpreter.

Length 1

Ð

Ah, the letter Eth. (Don't tell anyone, but it's my personal favorite.) This is the first example of one of Japt's defining features: Unicode shortcuts. Each one-byte character from ¡ to Þ has or will be assigned two or more chars to stand in for. Ð happens to stand for new Date(.

Another nifty feature is that missing parentheses are automatically added. This code transpiles to:

new Date()

Finally, implicit output: The last expression (separated by ;) is automatically sent to the output box. On my computer, the output comes up like so:

Sun Nov 29 2015 09:37:30 GMT-0500 (Eastern Standard Time)

One important thing to note is that in the interest of saving bytes, Japt replaces each close-paren with two close-parens, and each space with one. So instead of writing

Ð)+1

you would have to write

Ð +1

Length 2

Now we get to implicit input: N is pre-defined to the evaluated input. U, V, W, X, Y, and Z are set to the first six items. If there are less than six items in the input, the remaining vars are set to 0 instead.

Also, the Unicode shortcut ² is set to p2 . This means that the code is really Up2. All lower­case letters are reserved for methods, and are transpiled to e.g. .a(. This makes the code

U.p(2)

Japt has three main data types: strings, arrays, and numbers. And all three of these have different meanings for .p(). Here's what happens with the different input types:

  • string.p() = .repeat(), so the input is repeated twice and outputted.
  • array.p() = .push(), so 2 is added to the end of the array, and its new length is outputted.
  • number.p() = .pow() (hence the shortcut being ²), so the input is squared and outputted.

Length 3

Uæq

One of Japt's main strengths is its large selection of array manipulation functions. There are many helpful functions that we could use on arrays; more than the 26 lowercase letters can hold. So to get around this limit, we can use the lowercase accented letters in the range à-ÿ. æ returns the first item in the array that returns truthily when run through a function.

Another strength is auto-functions: if a lowercase letter is given in place of a function, it transpiles to e.g. function(c){return c.q()}.

So, this code returns the first item whose .q() returns with a truthy value. But what is truthy? As it turns out, almost everything: the only values in JS that are not truthy are "", 0, NaN, null, and undefined. And q is square root on numbers, which returns NaN for negatives and 0 for 0. So if the input is an array of numbers, this returns the first positive one:

-3   NaN    falsy
 0   0      falsy
-6   NaN    falsy
 7  ~2.646  truthy!
 4   2      truthy
-1   NaN    falsy

This example returns 7. But what about non-numbers? q splits a string into chars, and joins an array, so the only falsy value that's not a number will be the empty array:

[]       ""         falsy
[1,2,3]  "123"      truthy!
""       []         truthy
"abc"    ['a,'b,'c] truthy

The q trick has many other applications, which we will look at later.

Length 4

¡XcV

Let's take a look at functions now. ¡ stands for Um@, and @ stands for XYZ{, which is transpiled to function(X,Y,Z){. So here we have:

U.m(function(X,Y,Z){return X.c(V)})

This results in a whole tree of possible outputs, depending on the types of U and V:

  • If U is a number, m is Math.min and returns NaN.

  • If U is a string, m maps each char X to:

    • If V is not specified or 0, X's char code.
    • Otherwise, NaN.
  • If U is an array, m maps each item X to:

    • If X is a number: X.
    • If X is a string: if V||0 is within the length of X, the char code at V in X; otherwise, NaN.
    • If X is an array: X flattened (i.e. all items in sub-arrays are brought up to the base array).

Length 5

`HÁM!

Believe it or not, this doesn't give the user a ham. ;) On the contrary, it outputs a warm welcome:

Hello!

How does this work, you ask? Well, the secret lies in the backtick: Japt uses the shoco library for string compression. To compress text, you call Oc like so:

Oc"Hello!"

This will give you the compressed string. To decompress, you can do one of two things: 1) Use Od"...", or 2) wrap the text in backticks. This is why Japt is shorter in the "Hello, World!" challenge than almost every other language that doesn't have a built-in for "Hello, World!".

Oh, and one more thing: If you have a quotation mark or backtick (or dollar sign, or curly bracket, or parenthesis, or any combination of the above) at the end of a program, you can leave it off, saving an extra 1 or more bytes.

Length 6

U®¤¬r^

Lots of Unicode shortcuts here: ® stands for m_, and _ stands for Z{Z. ¤ stands for s2 , and ¬ stands for . Putting this all together, we get:

UmZ{Zs2 q r^

If the input is an array of numbers, this maps each item Z to Z.toString(2).split(""). But what is that r^ at the end? array.r() is the reduce function, which takes in a function of at least two parameters, and uses that function to combine each item with the previous value. As an example:

[0,1,2,3,4]rXY{X+Y

This reduces the array with addition. The result is 10; it works like this:

prev value: 0; next value: 1; result: 1
prev value: 1; next value: 2; result: 3
prev value: 3; next value: 3; result: 6
prev value: 6; next value: 4; result: 10.

But ^ is not a function, so what happens? Japt has a nice feature where if the first thing inside parentheses is an operator, it's transpiled to a function which takes in two arguments, and returns the result of the args being combined with that operator. So this whole program ends up as:

U.m(function(Z){return Z.s(2).q().r(function(a,b){return a^b})})

Which maps through each number, turns it to its an array of its binary digits, and finally returns 1 if this contains an odd number of 1s, and 0 otherwise.

Length 7

Uà ®r!-

More array manipulation: à returns all possible combinations of the array. You've already seen that ® is a shortcut for m_, and that r- would reduce by subtraction. But what does r!- mean? The difference is simple: an operator preceded by ! reverses the order of the resulting function's arguments. Here's exactly how this works:

Code  Transpiled
r-    .r(function(a,b){return a-b})
r!-   .r(function(a,b){return b-a})

After putting this all together, we end up with:

U.à().m(function(Z){return Z.r(function(a,b){return b-a})})

This takes all possible combinations of the input array, then reduces each by subtracting the previous result from the current item. For example, [1 3 7] becomes:

Comb.    Reduction       Result
1 3 7    3-1=2, 7-2=5    5
1 3      3-1=2           2
1 7      7-1=6           6
1        1=1             1
3 7      7-3=4           4
3        3=3             3
7        7=7             7

Length 8

Uf¬å+ ä^

Hooray for array manipulation! å is a cumulative reduce (i.e. like r, but returns an array of each intermediate value), and ä maps each adjacent pair of items through the function. As shown before, ¬ becomes , which performs square root on numbers. So if the input is an array of numbers, fq  filters out the non-positive ones, as shown in Snippet 3. Let's try it:

U   [1,2,-3,5,0,7]  [1,0,-1,1,1,0,1,1]
f¬  [1,2,5,7]       [1,1,1,1,1]
å+  [1,3,8,15]      [1,2,3,4,5]
ä^  [2,11,7]        [3,1,7,1]

q has even more potential in this area, which will be demonstrated in a future snippet. This program is obviously not super useful, but hey, messing around with math is fun. :)

Lots to come as I have time to add it!

Answered by ETHproductions on November 19, 2021

Treehugger

Treehugger is an interesting Brainf*** variant which operates on a downwards-infinite binary tree of byte values instead of on a rightwards-infinite tape. In addition to Brainf***'s 8 commands (two of which have been slightly redefined), it adds a ninth command, which will serve as my length 1 snippet.

A web interpreter can be found here.

Length 1 snippet: ^

The new command (although, in a literal Brainf***-to-Treehugger translation, it can be treated as equivalent to Brainf*** < instruction). Moves one position up the tree.

Length 2 snippet: <>

< moves one position down the current node's left branch, > moves one position down the current node's right branch. Thus, this will move the data pointer as shown here:

enter image description here

Length 3 snippet: +[]

An infinite loop, exactly like in Brainf***.

Length 5 snippet: ,[.,]

Another loaner from Brainf***: a cat program.

Answered by SJ-9000 on November 19, 2021

RPL (Redstone Programming Language) [and Minecraft]

This is a big stretch on whether or not we can consider this a real programming language or not, but we will try anyway. And, as these two "languages" are practically the same, I will combine them, sometimes post snippets in "Minecraft" language (redstone, etc) and sometimes in RPL. Also, since many snippets will be in Minecraft, I will post links to the pictures rather than the pictures themselves to save space. Additionally, all snippets will be of programming concepts in Minecraft, not general redstone (i.e. no redstone doors will appear). Characters will be counted in bytes (in RPL) or as according to this (in Minecraft).

Factoid:

RPL is a programming language by Tossha the Inventor that converts code into Minecraft redstone and command blocks. It can do input and output, loops, integer manipulation, trig functions, roots, and more.

Length 1:

A button (1 byte) is the simplest form of input in Minecraft. It also can start or stop a "program". Similarly, a lever (also 1 byte) is another form of input, and can also be used to both start and stop the program as it has an "on" and "off" state. Something to remember is that Minecraft is literally a 3D programming language, so where the button/lever is place in the program can make a huge difference.

Length 2:

A button attached to a redstone lamp is pretty much your very basic cat program. It takes the input (with a button or lever, either 0 or 1 (off or on)) and outputs it in the form as light from the lamp as either 0 or 1 (off or on).

enter image description here

Length 3:

As seen below, this one of the shortest source-code modifying programs (as you can modify the source at runtime with Minecraft!). Now, this specific one really has no use, but the concept can be combined with others to create some awesome programs (as to come with more upvotes). When run, this program removes its source of input, and makes itself unable to be run again. enter image description here

Length 4

This "snippet" actually shows two concepts: delay, and the NOT gate. Delay is made using certain redstone elements that have a redstone-tick delay. A redstone-tick is equal to one-tenth of a second. Different redstone components have different delays: a torch has a 1rt delay (1 redstone-tick), a comparator has a 1rt delay, a repeater can have a 1, 2, 3, or 4rt delay, depending on how it is set up. In this example, the redstone repeater is set to a 4rt delay.

Next is the NOT gate. The NOT gate takes an input an inverts it. So in this set up, the output will be on if the input is off, and the output will be off if the input is on.

Length 5

The OR gate is very easy to accomplish in Minecraft. Two inputs are connected to the same output. That is it. No funny trickery or anything, it's pretty simple.

enter image description here

Length 6

Here is a tip for compacting your "code". If you know the signal strength of two inputs are small enough to not interfere with the corresponding outputs, you can wire the redstone right nect to each other. In the example below, there is a simple hopper timer, which transfers items back and forth in about 0.5s in each hopper, conncected to comparators that output a signal strength of 1. This means that the two ouputs will not interfere with each other. In the example, the lamps are there for demonstration purposes only and don't count towards the total block count.

enter image description here

Answered by GamrCorps on November 19, 2021

Motorola MC14500B Machine Code


Factoid

Patented in 1977 by Motorola, Inc., the Motorola MC14500B is a CMOS processor in a 16-pin package. It has a 2-way data conductor (pin 3), and has 16 four-bit opcodes.


Length 1

Hexadecimal:

1

Binary:

0001

Explanation

1    Load data from the I/O pin to the register

With this 4-bit opcode, the register's value becomes the input value received by the I/O pin.


Length 2

Hexadecimal:

18

Binary:

0001 1000

Explanation

1    Load data from the I/O pin to the register
8    Output the register's value to the I/O pin

This single-byte operation, takes an input value via the I/O pin, and outputs via the same pin. Essentially, it is a cat program.


Length 3

Hexadecimal:

18F

Binary:

0001 1000 1111

Explanation

1    Load data from the I/O pin to the register
8    Output the register's value to the I/O pin
F    Jump back to the first opcode of the program

This will loop, taking an input and outputting its value. I used this snippet to demonstrate an infinite loop.


Length 4

Hexadecimal:

178F

Binary:

0001 0111 1000 1100

Explanation

1    Load data from the I/O pin to the register
7    If the register value is equal to the I/O pin's value, set the register to 1
8    Output the register's value to the I/O pin
F    Jump back to the first opcode of the program

This snippet will take an input, and output it's complement. This will continue in an infinite loop.


Length 5

Hexadecimal:

578EF

Binary:

0101 0111 1000 1110 1111

Explanation

5    Logical OR on the register and I/O pin
7    If the register value is equal to the I/O value, set the register to 1
8    Output the register's value to the I/O pin
E    Skip the next opcode if the register's value is 0
F    Jump back to the first opcode of the program

This snippet will take an input (essentially "Do you want me to stop looping?"). If the input is a 0, it will loop infinitely, but if the input is a 1, it will not loop.

If the input is 1, it will output 0 (for "not looping") and terminate, but if the input is 0, it will infinitely output 1.

Answered by Zach Gates on November 19, 2021

?????

Length 10 Snippet

ɟ⍞#rœэ¡²Ĩċ

Here's a really nasty infinite loop. It uses jQuery to press the "Run" button, which will execute the code that presses the "Run" button, which will execute... You get the idea. Even worse, it's impossible to stop without force-quitting Firefox itself, so be careful when running.

Also, this snippet uses compression: э¡²Ĩċ decompresses to click`.

Length 9 Snippet

ᵭꞒ↷+⬭+ᶑꞒ㘯

This is a fancy way of outputting Hello world. It uses the builtin Scrabble dictionary.

Length 8 Snippet

ʗć⁽ḊḞĒ`X

This outputs X to the canvas. Yes, ????? has a canvas.

Length 7 Snippet

ⓑᴙą1

Determines how even ï is. Notice that the ï at the end is missing (which is allowed through implicit input behavior).

Length 6 Snippet

⟮ɕṡ+ᶈ0

This is a quine. (copy block) stores any code after it into an array, ɕṡ is the character, and ᶈ0 gets the stored code.

Length 5 Snippet

ɟ⍘*Ĭ)

This removes all of the interpreter's HTML using jQuery. It's an example of how manipulative ????? can get with the interpreter's code.

Length 4 Snippet

¡МĂï

This calculates the factorial of ï. One difference: this uses a bignumber function to calculate values greater than 171 (JS's ordinary limit) accurately and quickly.

Length 3 Snippet

Мȫï

This outputs the ïth Fibonacci number. Мȫ is a math lib builtin.

Length 2 Snippet

⩤Ṥ

This outputs from 0 to 100. is the inclusive range function, and is the alias for 100. There are variables for numbers from 0 to 256.

Length 1 Snippet

ï

Here's a cat program! Quite simply, it gets user input and implicitly outputs it. Note that a 0-byte program would also be a cat program because of implicit input behavior.

Factoid

????? (or ESMin for any of y'all who can't see the doublestruck chars) is a code-golfing language (sort of) based on Javascript ES6. Its code page contains almost 1024 chars to account for the various aliases present.

Answered by Mama Fun Roll on November 19, 2021

O

Factoid

O is a programming language inspired by GolfScript, Pyth, K, and tons of other languages. It was made by Phase (me) over the summer of 2015, so it is relatively new. The interpreter was originally written in Java, but development has recently switched to a C interpreter. Here are some examples of the language.

Length 5

'69+o

This programs prints 69.

  • '6 pushes 6 as a string
    • ' pushes the next character in the program as a string to the stack
    • 6 is the next character, so it gets pushes as a string
  • 9 pushes the number 9 to the stack
  • + adds the top two elements of the stack. Since of them is a string, they get concatenated.
  • o outputs the result

Length 4

M]+o

This program gets the sum of all the digits of the input number. (1234 = 1 + 2 + 3 + 4 = 10)

  • M is a builtin macro that calls [i~.
    • [ Starts an array (which really acts like another stack)
    • i Gets an input from stdin and pushes it to the stack (the array in this case)
    • ~ Evaluates the top of the stack (the input) as O code, which pushes each digit of the input number to the stack.
  • ] Closes the array, pushes it to the stack
  • + Folds the array by adding all the elements together
  • o Outputs the sum of the digits to stdout.

It's a pretty complicated program for only being 4 bytes!

Length 3

{1}

O supports CodeBlocks like GolfScript and CJam. This is a CodeBlock that pushes the number 1 to the stack when it is run. Just creating a CodeBlock pushes the block itself to the stack, without running it. We could assign it to a variable, or use ~ to run it.

Length 2

Ao

A pushes 10 to the stack. o pops the top of the stack and outputs it to STDOUT. This program outputs 10 to the screen.

Length 1

1

Any number literal will be pushed to the stack as an integer. The stack is not outputted when the code ends (though this may change soon!), so the program exits without outputting anything.

Answered by jado on November 19, 2021

TeaScript

Length 6 Snippet

r×ߥl©

This looks like gibberish so here's the ungolfed version: r(x)m(#$P(l)).

This returns a list of first n numbers and if they are prime. An output for the input 5 would be: false,false,true,true,false

Length 4 Snippet

£lc)

Now we're getting somewhere. This loops through each character of the input and replaces the character with it's character code.

Length 3 Snippet

¥x)

Checks if the input is prime. Returns true or false respectively.

Length 2 Snippet

xv

x is the input, v is a function which will reverse x. This essentially reverses the input.

Length 1 Snippet

M

The M character is preset to return a random number


Try any of these online

Factoid:

TeaScript was born after I got fed up with JavaScript's incredibly long String.fromCharCode function. It was originally made to have just shortened property names but TeaScript has grown quickly.

Answered by Downgoat on November 19, 2021

Minkolang

Length 6 snippet (try it)

$n$*N.

This multiplies together the numbers in the input. $n reads in all of the numbers from input, $* multiplies together the whole stack, N outputs as a number, and . stops. The linked example has 5 6 0.1 -3 (1+1j) (1-1j) as the input and (-18+0j) as the output, thus proving that Minkolang can handle integers, floats, and complex numbers.

It's also worth noting that Minkolang disregards non-numeric characters. In this example, the input is This5Shows6That0.1non-numeric-3characters(1+1j)are(1-1j)disregarded1. and the output is the same as before.

Length 5 snippet (try it)

od?.O

cat program. o reads in a character from input and pushes its ASCII code onto the stack (0 if the input is empty). d then duplicates the top of stack (the character that was just read in). ? is a conditional trampoline, which jumps the next instruction of the top of stack is not 0. If the input was empty, then the . is not jumped and the program halts. Otherwise, O outputs the top of stack as a character.

Here is a 5-byte solution to reverse cat (try it):

$o$O.

$o reads in the whole input as characters, $O outputs the whole stack as characters, and . halts.

Length 4 snippet (try it)

V  .

Minkolang's spaceship can be boosted across empty space, which is done with V. This enables it to get to the ., where the program halts.

Length 3 snippet (try it)

3@.

This demonstrates the unconditional n-trampoline, @ (its cousins are ! ? &). Minkolang's codebox is toroidal, meaning that when the spaceship goes off any edge, it reappears on the opposite edge. Here, 3@ skips the next three instructions in the direction of travel, namely .3@, in that order. So it lands directly on the ., which stops the program.

Length 2 snippet (try it)

N.

This is the shortest program producing output (and stopping). N pops the top of stack and outputs it as an integer and . stops execution. When the stack is empty, any operation that tries to pop from the stack will pop a 0 as it has a bottomless well of 0s. Thus, N will output 0 (with a trailing space) and then stop.

Length 1 snippet (try it)

<empty space>

The shortest infinite loop in Minkolang. But this one has a catch. Unlike Befunge or ><>, this one loops through time. In fact, any column of empty spaces is a potential infinite loop.

Factoid

Minkolang is a Minkowskian (2+1)D stack-based semi-golfing language. The "Minkowskian (2+1)D" part simply means that there are two dimensions of space and one of time. The spaceship (or program counter, if you prefer) travels through time when it's not traveling through space. This might sound weird, but consider this: you are barely moving, sitting in your chair. Even if you include the motions imparted by the Earth's rotation, the Earth's journey around the Sun, and the Sun's journey around the Milky Way, it's still only a tiny fraction of the speed of light. So you move through time at almost exactly the rate of one second per second. If, however, you are moving through space at the speed of light, then time stops. Likewise, the spaceship in Minkolang moves through time when it can, when it's not moving through space! Any instruction that does not change its direction preserves it, and wherever there is a space that the spaceship is not boosted across, it starts moving through time (represented as the layers of the program).

Answered by El'endia Starman on November 19, 2021

ShapeScript

Length 6 snippet

"%c"@%

ShapeScript has no type casts, but Python's % can be used to work around this limitation. This snippet, e.g., pops an integer from the stack and pushes the singleton string of the corresponding Unicode character in return.

Length 5 snippet

'"A"'

This is a string that, when evaluated, pushes the singleton string A on the stack. There is no way to escape a quote in ShapeScript, so two different kinds of quotes are required to use strings in evaluated strings.

Length 4 snippet

01-?

This calculates -1 and then pushes a copy (?) of the bottom-most item on top of the stack. Since there are no variables, leaving things on the bottom to access them later is a common technique.

Length 3 snippet

123

Despite what it may look like, this actually pushes three integers on the stack. Any integer above 9 or below 0 has to be pushed as angebraic sum of products of integers.

Length 2 snippet

*!

With a Boolean and a string on the stack, * pushes the unmodified string for True and and empty string for False, which ! then evaluates. This is the closest ShapeScript has to a conditional operator.

Length 1 snippet

!

Discounting that it can no longer take input, this is a fully compliant ShapeScript interpreter.

Factoid

I created ShapeScript as one half of my submission to Create a programming language that only appears to be unusable as a simple, stack-based language with a simple syntax.

While ShapeScript is far from unusable, it does not have traditional loops, conditionals or variables, can modify only the two topmost stack items, can modify strings only using split and join, etc.

Answered by Dennis on November 19, 2021

Thue

Thue (the correct pronounciation is either "TOO-eh" or "TOO-ay", I've heard both) is a language based on nondeterministic string rewriting. It is presumably named after Norwegian mathematitcian Axel Thue. A program consists of a list of zero or more substitution rules (terminated by the null rule), followed by a string indicating the initial state.

Length 1: ~

Prepending a tilde to the right side of a rule is the language's only way to produce output. Basically, when that rule is applied, the target substring, instead of being replaced with the string on the right side of the rule, is removed and the remainder of the string (everything after the ~) on the right side of the rule is printed to the output. (A rule may be applied to any substring of the state which matches the rule's left side.)

When used in this way, a tilde is often read as "print".

Length 3: ::=

These three characters (typically read as "can mean") are used to separate the left side of a rule from the right side.

When both sides of a rule are empty, it serves as the null rule, which terminates the rule list (what should happen when only the left side is empty is undefined, most implementations treat it as equivalent to both sides being empty. It is, however, perfectly valid for only the right side to be empty.)

Length 4: 0::=

This is a complete rule dictating that instances of the substring "0" may be removed and discarded.

Length 5: 0::=0

This is a complete rule dictating that instances of the substring "0" may be replaced with... itself. This can be used to construct a simple infinite loop, as seen here.

Length 6: ab::=~

This is a complete rule dictating that instances of the substring "ab" may be removed, printing the empty string. As the specs don't actually provide any way of printing a newline, some implementations will do this when the empty string is printed.

Length 7: a::=:::

When three colons are used as the right side of a rule, this means the replacement string should be taken from STDIN. Thus, this rule dictates that instances of the substring "a" can be replaced with strings from STDIN.

Triple colons used in this way are read as "input".

Answered by SuperJedi224 on November 19, 2021

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.

Answered by user45941 on November 19, 2021

Simplex

Version is the latest, unless otherwise specified; interpreter is currently down; docs a little unupdated as of now.


6-vote

1(D)10
1      ~~ sets current byte to 1
 ( )10 ~~ repeat inner 100 times
  D    ~~ double current byte
       ~~ implicitly output byte

This outputs 2^10 in its exact form. Simplex has something I liked to call “Infinite Capacity Numerics®”. It can be a bit slow sometimes, but is/will be highly precise.

5-vote

"hi"g

Writes a string hi to the strip and outputs it.

4-vote

eRPE

Outputs eπ ≈ 23.1406926328. e is Euler's number, R goes right in the strip, P is π, and E is exponentiation. Output is implicit.

3-vote

i¢I

A little code that takes numeric input, terminates if input = zero, otherwise increments the byte. Implicitly outputs the result. (It's also French! (ish): ici => here)

2-vote

MO

Shortest way to create a bounds error; M decrements the byte and O goes to the current byteth position in the source code…maybe I should include negative source codes…nah, who'd go for it?

1-vote

5

Not very interesting, but writes 5 to the current strip's first cell. (Also implicitly outputs 5.)

0-vote

Simplex is a golfing language which functions similar to BrainF***, made by me. It is very much a work in progress, but has about 60 standard commands. It is composed of a singular field, which holds a bottom-closed, top-open, infinite amount of strips, each of which contains a right-open, left-closed, infinite amount of cells and a pointer. The field can be visualized as thus:

5: [0 0 0 0 0 0 0 ... ]
    ^
4: [0 0 0 0 0 0 0 ... ]
    ^
3: [0 0 0 0 0 0 0 ... ]
    ^
2: [0 0 0 0 0 0 0 ... ]
    ^
1: [0 0 0 0 0 0 0 ... ]
    ^
0: [0 0 0 0 0 0 0 ... ]
    ^

Each pointer moves independent of other pointers. Typically, only one or two strips are utilized in a single program.

Answered by Conor O'Brien on November 19, 2021

Carrot

4-byte code

0^*2

(Prints 000)

I have chosen to use this snippet because of its weirdness. So the first bit of the code says that the stack is 0. Then the * is string multiplication. It multiplies "0" 2 times. One would expect the output to be 00, but no! 000 is outputted instead. So the stack is repeated 2+1=3 times, which gives 000. This trick is useful for golfing when you want to output the stack 10 times. Instead of going (stack)^*10, you will do (stack)^*9 because it saves one byte!

3-byte code

$^P

The $ is the alternative to # for taking input. In the future I hope to distinguish these two similar functions... Coming back to the topic, we see the caret ^ for the first time. This is to differentiate the stack from the commands. Then comes the P. This checks if the stack is a prime or not(works for the number 1). This primality checking works on the stack both as a string or as a number. This "special power" of P can make it more useful for code-golfing.

2-byte code

#A

Outputs inputA. If the input is C, then the output would be CA

This piece of code shows two interesting properties of Carrot:

  1. One is that the string "A" does not need to be enclosed in quotes in the stack.
  2. The other one is that the plus "+" sign for concatenation is not required in the stack. The two strings, the input and the "A", get joined together automatically.

1-byte code

#

This is a simple program that prints the output as it is. The # can be used in the commands or the stack section of the program. The caret ^ is not required because we do not wish to use commands.

Factoid: Carrot is a language made by me, Kritixi Lithos, based on this carrot meme of PPCG. Every Carrot program as of version ^2 must have a ^ in it. The structure of every program is as follows: stack^commands.

Answered by user41805 on November 19, 2021

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

IiO

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.

Answered by Addison Crump on November 19, 2021

JacobFck

JacobFck is a stack based esoteric language written in C#. It is capable of all basic operations as well as some more common operations. It is a slight mix of BrainFuck like syntax and Forth. The link above links to the JacobFck GitHub.

Length 1

>

This is one of the simplest instructions. It writes to the screen whatever is at the top of the stack.

Length 2

^5

The ^ instruction tells the interpreter that we are going to be pushing data (either number or register value) onto the stack. In this case, the number 5.

Length 3

"s"

Strings (encased in "") are automatically pushed to the top of the stack, and n t r are all supported escape codes.

Length 4

^2<+

This code would push 2 to the stack with the ^ instruction, push user input to the stack with the < instruction, and add the two together by popping them off the stack and pushing the result to the top.

Length 5

:a<_a

This code is an example of an infinite loop. :a declared the label a. < is the instruction to prompt the user for input. _a goes to the label a.

Answered by Jacob Misirian on November 19, 2021

Snap!

Snap! is a language based off of Scratch. Scratch answer: here
Note: These are things specific to Snap.

Factoid

Snap!'s old name was BYOB, for Build Your Own Blocks. The creators were forced to change it because some teachers at Berkeley, where it was based, had no sense of humor.

Length 1 Snippet

unicode65asletter

Unicode support is available!

Length 2 Snippet

This one only works if you load the toolblocks (the smaller button on the page). IMO, you should always load the toolblocks.

b2r

You can convert blocks to reporters (things that contain numbers). This way, whenever a reporter would be needed, you can use a block!

Length 3 Snippet

Ternary operators and writing to the screen! This will print hi because an empty boolean slot is FALSE.

Answered by user46167 on November 19, 2021

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 defx{}

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 Xbye

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.

Answered by yo' on November 19, 2021

PoGo

Factoid

PoGo is an esoteric programming language that consists only of two letter commands with one vowel and one consonant each, designed to make the source code read funny. It operates on a two dimensional memory grid and three different stacks.

2 Characters

qi

Output:

poqigo

qi is one of the special purpose output commands, just for fun (others include wo wich outputs "Hello, world!"). What's special about poqigo? Wait for the 6 characters program!

4 Characers

isis

Output (example):

What is my purpose?
What is my purpose?

is is another special purpose output command, specified as "have an existentialist crisis". The message is choosen randomly, but at least in the official implementation it is memoized so that calling is twice gives the same output twice.

6 Characters

poqigo

Output:

poqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigopoqigo[...]

In the documentation, poqigo is mentioned as an example for a quine and obviously that's the only purpose of the qi command, but it actually isn't a real quine since it outputs itself infinitely, not just once.

With this example we learn the basics of flow control in PoGo. You use a call stack (the "po" stack):

  • po - add current position in code to the top of the po stack
  • go - pop the most recent po location off the stack and jump there

So po ... go produces a loop and if you don't use any conditions to break out of it, it's an endless loop

Answered by Fabian Schmengler on November 19, 2021

EGSHEL (the Extensible Golfing Scripting High Efficiency Language) v0.1

Currently in development, EGSHEL is a highly extensible turing-complete object-oriented stack-aware scripting language intended mostly for golfing but which, especially due to a Pythonic module-importing structure, is designed to be useful in other ways, as a general purpose language. It's influenced by Pyth, LOLCODE, GolfScript, Python, BrainFuck, and more.
Incidentally, its error-allowing parser and ignorance of unused or explicitly undefined characters make it very useful for polyglots with other, "real" languages like C, Python and Javascript.

Factoid: LOLScript EGSHEL has two basic parser modes: Concise, which binds builtins to lowercase letters and makes everything tiny, and Verbose, the default, which can can parse Concise code but, as the name suggests, is less tiny and more readable. The name EGSHEL is both a backronym and intended to convey that due to implicit, inferential types and other such features.

Originally designated LOLGolf LOLScript, it's clear from where LOLScript gets its name (which will probably change soon): LOLCODE. I was trying to make a meaningful program for Mystery String Printer in less than 128 bytes but LC has more than that in boilerplate just to make a loop.
(In practice, however, LS does not look or work at all remotely like LC. The first spec isn't even done but all we've copied from LC into LS so far is "vsb" to print strings (from LC's VISIBLE builtin.))


1 Char:

;

A semicolon is not so interesting but extremely useful. It can turn lines that would otherwise need to end in a newline, into a continuous line, and when found after a statement within either the first or last 3 lines of the file, sets some interesting mode-related options.
On its own line, though, it denotes the respective beginning or end of a readable file and if only one is found near either the top or bottom of the file, it gives execute precedence to that "side" of the file.
Execute precedence is something more easily explained with more chars but basically, it sets the initial reading direction: up or down the file.
In Concise mode, since Concise programs are almost always one line, an otherwise unecessary leading or trailing semicolon denotes the left/right reading direction on a per-character basis. But, I need more votes to explain further.

2 Chars:

-|

A hyphen directly followed by a vertical bar is, at least for now, a single line comment initiator in Verbose mode.
In Concise mode, unless the Concise code is embedded within a Verbose function or block, there are no comments and this denotes something nothing, yet.

If a -| is found more two or more spaces after a valid grouping of characters on a line in a Concise block in an otherwise Verbose script, it is a single line comment.

3 Chars:

1~B

Finally something unique! Take a guess as to what this does... If you guessed that it results in the second last (zero-indexed) history index of B, then you would be right!
History indicies allow direct access to a given variable's given 0 (represented by a solo tilde preceding a var) - Fh-th previous value.
What, you may ask, is the point? Well, as an example, when you use a similar statement ~1B, the result is the two (0 & 1) previous variables and B's current value concatenated based on their types. EGSHEL is dynamically typed and object-oriented thus it's up to the programmer to explicitly cast otherwise implicit types when needed. ~*B results in all previous values of B concatenated, incidentally.

4 Chars

#0(y

Calls the first defined anonymous function in a file with y as an argument. functions are defined like $foo(args{body} but if you leave out the function name foo, it becomes anonymous, is put into a numbered list, and you must call it as above. normal functions are called with their name as expected: foo(args.

5 Chars:

{:x:y}

Simple for loop, for i (that's i for Implied Imaginary) in x do y. More colons can expand this into a first, second, third C-style loop.

Answered by cat on November 19, 2021

ArnoldC

Factoid:

ArnoldC, a programming language based on Arnold Schwarzenegger's one-liners, was created to "to discover new meanings from the Arnold movies with the means of computer science."

Length 1 snippet:

1

Just like many other languages, ArnoldC considers 1 to be true and 0 to be false.

Length 2 snippet:

""

Two quotation marks are used to make a String.

Length 5 snippet:

CHILL

Chill ends a while loop.

Length 6 snippet:

I LIED

The Arnold quote "I LIED" is equivalent to the value 0

GET UP is the addition operator.

Length 7 snippet:

declaim

The -declaim flag can be passed to the compiler to produce an audio file from the source code.

Length 8 snippet:

BULLSHIT

An else statement to be placed after an if statement.

Length 9 snippet:

GET UP 33

GET UP is the addition operator in ArnoldC, so the above code snippet can increment an integer by 33.

Length 10 snippet:

ENOUGH TALK

ENOUGH TALK is placed after GET TO THE CHOPPER to end the assignment of a variable.

Answered by LoadingPleaseWait on November 19, 2021

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!

Answered by Arcturus on November 19, 2021

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

Answered by Addison Crump on November 19, 2021

OpenSCAD

OpenSCAD is a language used to create parametric and accurate 3d models using nothing but code. Note: I refer to CSG multiple times in this post; this stands for Constructive Solid Geometry. This means constructing a model through a combination of combining objects, subtracting objects, and intersecting objects.

Factoid:

Since a .scad file is plain text, it occupies very little space, and you can use tools like diff effectively.

Length 1:

Well, there isn't too much you can do with one character, but one very useful character is the debug modifier:

#

This character can be placed in front of any CSG tree to highlight it, even if it would be invisible in the final output (such as if the CSG object was subtracted from another object). I'm not allowed to write any more code to explain this, so I'll use pictures.

Without the modifier:

No modifier

With the modifier:

With modifier

(Image Source: OpenSCAD User Manual, Wikibooks, CC-BY-SA)

Length 2:

In OpenSCAD, you can create simple animations. How, you ask? This is done using a special variable for animation:

$t

This variable repeatedly loops from 0 to 1, which your code can use to change the position of an object, rotate an object, or do pretty much anything when combined with control flow structures. OpenSCAD can dump png frames at user specified intervals to create videos and/or gifs.

Adding a single line of code to a program (in this case, one of the examples, which also happens to be the OpenSCAD logo), and running the output through a gif maker can turn it into an animation like this: Rotating OpenSCAD logo

Length 3:

There are a wealth of libraries in OpenSCAD, and one way to access them is via the command:

use

There are actually two commands with similar functionality, but the other one has too many bytes. The main difference is that any top-level code (code outside a function/module) isn't executed with use, while it is executed for the other command. Both commands must be placed before any use of imported functions.

There are a couple of widely used libraries (Note that some of these should be added to the project with the other command instead):

  • MCAD- this contains basic utilities (more shapes, gears, some math, etc), and often is installed automatically with OpenSCAD.
  • Write.scad- Many of it's functions have been superseded by built-in functions in OpenSCAD, but it allows you to do a little more than the built-in functions can do (write curved text, for example).
  • BOLTS- This extensive library allows you to use standard hardware parts (and some non-standard hardware) in your projects.
  • The General Library of Relativity- Allows creating and positioning of objects relative to other objects.
  • String Theory- Made by the same person as Relativity, this provides various string utilities, along with regex functionality.

Length 4:

4 bytes is in that weird range where you can't really show off special variables or 1-character modifiers, but it's too short to really demonstrate the usage of a keyword.

However, it is the smallest whole program that isn't empty (or made up of only whitespace and semicolons) that compiles/runs without an error:

a=1;

This just assigns 1 to the constant a. In OpenSCAD, almost everything is a constant within its scope. Recursion, iteration, and defining separate constants are two common ways to circumvent this limitation. Note that OpenSCAD is dynamically typed.

Length 5:

Much of OpenSCAD's power comes from its conditional branching. Assuming that a is a boolean value, you can write:

if(a)

Alternatively, you can put in any expression that evaluates to a boolean. This may be followed by a single statement, or by a code block surrounded by braces. The if statement shouldn't be used to conditionally assign variables, however—Any variable re-assignment creates a scope for the new variable which effectively shadows, not replaces the original variable. Conditional variable assignment must be done on declaration of the variable, with the ternary operator.

Length 6:

This one is really cool:

hull()

It's the digital equivalent of wrapping a piece of plastic wrap around an object:

Without hull:

No hull

With hull:

Yes hull

Length 7:

This one isn't too exciting, but it is very useful:

[0:2:6]

This evaluates to an array. The first number is the starting value, the last number is the ending value, and the (optional) middle number is the step. For example, the previous line of code would evaluate to [0,2,4,6]. Arrays can be nested (jagged arrays and different levels of nesting are allowed) and they can be assigned to a variable.

Length 8:

This is one of the three main CSG operations in OpenSCAD:

union(){

Now would be a good time to talk about the tree structures in OpenSCAD. In OpenSCAD, every object (in terms of 3D modeling, not OOP; OpenSCAD is definitely not OOP) is a node on a tree, and each can contain sub-trees.

Every OpenSCAD model is built from a handful of built-in primitive objects (these primarily act as end-nodes), and various built-in operations (these typically contain their own sub-trees). Additionally, you can define your own operations that either transform their sub-trees, or create a model on its own—but that's a topic for later on.

Back to union: this operator wraps everything in its sub-tree into one node (but doesn't do anything to the objects themselves), so that they can be treated as one whole unit when used in other operations. It may not do much on its own, but when combined with other operations, it can be a vital tool.

Length 9:

Here's a mouthful:

minkowski

The minkowski function involves taking the minkowski sum of an object. This one is a bit weird, as it is taking one shape, and moving it around the surface of another object. It's hard to explain in words, so an image is definitely helpful.

Non-summed:

Not summed

Summed:

Summed

The same process can also be extrapolated into the third dimension:

3D Non Summed 3D Summed

Note that when using this, it can take a while for it to render, especially for more complex objects.

Length 10:

Here is another important CSG operation:

difference

This takes the first element of its sub-tree, and "subtracts" every other object in the sub-tree from it.

For example, in this picture, the cylinder is being subtracted from the cube. Note that the debug modifier is used to make the cylinder visible:

Difference

Length 11:

Finally, there are enough bytes to be able to define a module:

module a(){

A module in OpenSCAD can define an object, operate on objects, or both. Everything (including the built-ins) that creates or modifies objects (not numbers, booleans, arrays, or strings, though; those are for functions, which I'll talk about in another section) is a module. The module can also accept variables (and define default values), though you have to be careful, as OpenSCAD is dynamically typed. Some modules can operate on their sub-trees; however, most modules won't do anything if they are passed a sub-tree. More info can be found here.

Length 12:

Finally, the third major CSG operation

intersection

This takes the intersection of two objects.

For example, the intersection of these two objects:

Not Intersected

would be:

Intersected

Note that intersection doesn't work as expected when working with for loops, but there is a way around that. This may to change in future versions, however.

Length 13:

Everything so far has been a yellow (or translucent red) color. How boring! You can spice it up with colors like "mediumspringgreen" and such, but since that would put this over the length limit, I'll choose a different color:

color("cyan")

As expected, this changes the color of its subtree:

It's also "aqua"

The color module accepts any of the standard CSS/SVG color names, and can also accept a vector of RGB colors (scaled from 0-1, not 0-255) with an optional transparency. More info on color here.

Length 14:

OpenSCAD includes the for loop, for simple iteration:

for(i=[0:2:8])

There are a couple finer points when dealing with for loops. For one, the loop variable can iterate over any array. As stated in the Length 7 snippet, [0:2:8] simply evaluates to [0,2,4,6,8] when looped through. Since OpenSCAD isn't type safe, make sure that the loop body can handle the loop effectively. Besides a special for loop for dealing with intersections, there are a couple variations that greatly expand the for loop's capability that I'll describe when there are more bytes.

Length 15:

Adding to the list of built-in modules:

scale([x,y,z]){

(Note that [x,y,z] is a vector, which is basically an array in OpenSCAD. You can substitute the whole expression for a variable that equals a vector.) When applied to a sphere, you can do things like stretch it so it becomes a blimp-like shape:

Blimp

This command can be applied to any sub-tree and have a similar effect.

Length 16:

resize([5,8,10])

This command takes the bounding box of the subtree, and stretches (or shrinks) each axis to fit in a new bounding box. For example, say you have a sphere of radius 10:

Sphere

If you resize it to a 5x8x10 bounding box, it becomes:

Whatever this is

Length 17:

linear_extrude(h)

(where h means height)

If I take this 2D square (size 10x10):

Square

and I apply a linear extrude with a height of 5 to the square, then I get a rectangular prism:

Rectangular prism

Length 18:

While you can't set arrays from inside a for loop (the variable inside the for loop shadows the variable in the wider scope), OpenSCAD compensates by adding list comprehensions.

[for(i=[1:10])i*2]

This list comprehension iterates i from 1 through 10, and for each value of i, the result is 2i. This expression results in the array [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]. Note that this array could have been produced with [2:2:20].

Length 19:

import("model.stl");

(Note that STL is a file format for 3D models. It contains a triangular mesh of all of the surfaces in a model.)

If I save the hilbert cube model from here as model.stl in the same folder as the .scad file, OpenSCAD allows you to use it as a component of the model (e.g. you can perform CSG operations on the model).

Hilbert cube

Length 20:

Let's do some animation!

$vpr= [45,0,$t*360];

$vpr is a special variable in OpenSCAD. It contains the rotation of the viewport ($vpt and $vpd contain the translation and distance, respectively). If you assign them a new value, the viewport changes to that value.

As stated earlier, $t contains a value between 0 and 1.

To start with animation, click View > Animate. That will bring up a bar like this:

Bar

Time will automatically change when you configure the other two values. This becomes the value of $t.

Steps means the amount of steps that $t will go through between 0 and 1.

FPS is the amount of steps OpenSCAD will go through every second.

If "Dump Pictures" is selected, as OpenSCAD goes through the animation, it will save the pictures sequentially.

With the above code, 30 steps, and 10 FPS, I get this exciting animation:

Super exciting

Of course, you can use $t in other places as necessary.

Answered by Daniel M. on November 19, 2021

Math++

The latest addition to my arsenal of custom languages. Also the first to include a mathematical expression parser. Operates exclusively on 64-bit IEEE754 floats.

Control flow consists exclusively of evaluated gotoes.

Length 1 snippet: ?

A special expression that returns a number taken from the input.

Length 2 snippet: !0

Returns NOT 0, which obviously equals 1.

(If you call the ! operator on any value other than 0, it returns 0)

Length 3 snippet: 0>$

This is the first snippet here to show the > symbol, which, in this language, is not a greater than operator but rather a symbol to separate an expression from its (optional) target designator. (The target designator out, meaning that the result should be printed to the output, is the default.) In this case, the target designator $ indicates that the result should be floored and then stored to the instruction pointer (thereby going to that number line.) Going to line 0 is considered an exit statement, going to any other out-of-bounds line number triggers an exception.

Length 4 snippet: _a>a

Floors the value stored in a, then stores the result back to a.

Length 5 snippet: 1>{0}

Associates the value 1 to the key 0 in the map.

Length 6 snippet: cbrt$e

An expression that yields enter image description here

($e is Euler's constant, just plain e is a variable; the language also supports pi ($pi) and the golden ratio ($phi))

Length 7 snippet: 9*$rand

$rand returns a random floating-point value greater than or equal to 0 but less then 1. Therefore, this expression returns a random floating-point value greater than or equal to 0 but less then 9.

Length 8 snippet: sin$pi|1

We've got logical operators, too!

This should return 1, but because of a rounding error in the evaluation of sin$pi, it yields 1.2246467991473532E-16. Darn you, IEEE.

Answered by SuperJedi224 on November 19, 2021

Poslin

Factoid

Poslin is a concatenative language with strict postfix notation and a metacircular interpreter.

It is similar to the language described in EWD28 in principle but is not inspired by it.

Unlike the language described in the linked paper, the immediateness of a symbol is definable in code, allowing the programmer to define almost arbitrary new syntax. Things like the symbol table and lexical environments exist as first class objects.

Every token in Poslin is surrounded by whitespace.

Length 1 snippet

!

This is actually not a working program. Executing it in a fresh session gives a stack-bottom-error. This operation is immediate and executes the operation on top of the current stack. Without it, nothing would ever happen.

Length 2 snippet

&+

This also isn't a working program. & is an immediate operation to compile something into a thread. &+ also is an immediate operation, but after compiling it executes the operation stored at a place accessible via HOOK compilation-hook slot-sub-get.

This way users can define their own optimization passes.

Length 3 snippet

[ ]

This creates an empty stack. [] also creates an empty stack ad does so much more efficiently. That's because Poslin works with something which is called the path. The path is a stack of environments, where environments are kind of like prototyped objects, that is, they are mappings (from symbols to bindings) which can have parent-environments. When some object is found by the reader which is not an immediate symbol, it is put onto a stack which is saved in a binding (besides the path, the return stack and arguably streams the only mutable data structures in poslin) which is found under the symbol STACK in the environment on top of the path.

[ puts a new environment onto the path which contains a fresh binding containing an empty stack for it's STACK. ] pops the topmost environment off the path and then extracts the stack saved in the binding in its STACK slot.

[] just constantly returns an empty stack.

[], [ and ] are all immediate.

Length 4 snippet

'& &

There is no single operation in poslin which defines a new operation. Well, actually there are several, but they're all defined in the standard library, which is written in a subset of poslin called "poslin0".

& has the purpose of transforming a given object into a thread.

For threads it's just an identity operation.

Symbols are looked up in an environment saved in a binding in the OP slot of the environment on top of the path.

Stacks are converted by turning everything but threads into constant functions returning that object and then concatenating together the resulting objects into one thread. At least, that's roughly how it works. This means, of course, that any operation which should be called inside a thread created this way needs to be turned into a thread via & before the calling thread is constructed.

Every other object is turned into a constant thread returning that exact object.

'& is special syntax: The leading ' tells the reader that this is a quotation, that is, everything after the ' is interpreted as a symbol (including any other 's) and then just put onto the current stack without checking for immediateness.

So the given snippet returns the thread of our poslin compiler. It is used in the operation ]o, which defines a new operation. With the knowledge given up to this point, you might be able to figure out how defining an operation works conceptually, even if you are missing some important operations.

Length 5 snippet

$:
":

This is the string you'd normally see as """ in most other languages, that is, the string containing exactly the double-quote character.

The character $ starts a delimited string. A delimited string has a delimiter, which is given between the $ and the next newline. The string contains all characters between that newline and the next occurence of the delimiter followed by some kind of whitespace.

If the delimiter occurs and is not followed by whitespace, it is a part of the string and does not function as delimiter. Remember: Every token in Poslin is surrounded by whitespace.

So, the given string could also be written as

$"
""

or even """, as Poslin recognizes the usual syntax for strings, too. It does not recognize any escape sequences.

Length 6 snippet

+ call

This is almost equivalent to + &. The important difference is that + & returns the thread of + while + call returns a thread which reads the binding which holds the definition of + and then calls the content of that binding. So, if you expect that the definition of + might change and you need to call the new definition instead of the old one, use + call.

This is necessary for defining recursive operations. There is no way to insert a thread into itself, so the binding which is later intended to contain the thread is inserted instead via call and after the thread is constructed it is written into that binding.

Length 7 snippet

. ? ! !

? consumes the top three elements off the stack. The third from the top needs to be a boolean value. If it is true, the second from top is put back onto the stack, if it is false the first from top is put back onto the stack.

. is simply the no-op.

So this is an immediate when. Imagine the following stack:

[ 2 TRUE P{negation} ]

This proceeds as follows with the above sequence:

[ 2 TRUE P{negation} . ]
[ 2 TRUE P{negation} . ? ]
[ 2 P{negation} ]
[ -2 ]

Whereas if the stack is

[ 2 FALSE P{negation} ]

It proceeds thus:

[ 2 FALSE P{negation} . ]
[ 2 FALSE P{negation} . ? ]
[ 2 . ]
[ 2 ]

Answered by Thomas Bartscher on November 19, 2021

Beam

Factoid

Beam is a 2-dimensional language designed in 2010 by an Esolangs Wiki user named Feuermonster, and was originally implemented in 2012. It was re-discovered by me while looking for an interesting language with which to answer the famous "Hello, World!" catalog. The official interpreter has been lost, but PPCG user MickyT has developed a Stack Snippet interpreter.

Beam is based off of three storage values:

  • the beam, the primary storage; holds one unsigned 8-bit integer.
  • the store, the secondary storage; holds one unsigned 32-bit integer.
  • the memory, a (theoretically) infinite tape of unsigned 8-bit integers.

Length 1 snippet

H

Yay, our first full program! Unfortunately, we can hardly do anything in just 1 byte. H simply halts execution of the program, so from this, we get no output at all.

Length 2 snippet

:H

Now we get a chance to see some output. : prints the value of the beam as a number, so this program outputs 0. If we were to drop the H, it would still print 0, but it would also give us the error message Beam is lost in space. This error occurs anytime the beam travels beyond the bounds of the program.

Length 3 snippet

r@H

First lessons in inputting: r sets the beam to the char code of the next character in STDIN. @ is like :, except that it outputs as a character instead of a number. All in all, this program outputs the next character from the input. Not that useful, but pretty decent for 3 bytes. ;)

Length 4 snippet

++:H

Here we have the new character +. Can you guess what it does? (Hint: this program outputs the number 2.)

Length 5 snippet

v
:H

Finally, a chance to use Beam's 2D instruction plane! Beam has four arrows ^v<>, which set the direction of the beam, and four mirrors /|_, which reflect the beam in another direction. It also has several conditional direction changers, which we'll get into in a little bit.

Length 6 snippet

)n+!
 H

Here we demonstrate a few of the conditional statements. ) and ( change direction to left or right if the store <> 0. ! and ? reverse the flow direction depending of the value of the beam. n and u change the flow direction to up or down if the beam != the store.
So in the snippet above, ) does not change the direction since the store is 0, the flow continues through n as the beam and store are both 0. + increments the beam. ! reverses the flow since the beam is now 1. + the beam again. n now changes the flow direction down since the beam is 2 while the store is still 0. Halt the program.

Length 7 snippet

+P+:p:H

Bit of a boring snippet, but it demonstrates the setting and retrieving of memory values. P will set the memory at store position to the beam value. p will set the beam to the value at the stores memory position. In this example the beam is incremented to one. Memory location 0(store) is set to 1(beam). The beam is incremented and the value printed. Memory location 0 is retrieved into the beam and printed. The output is 21

More to come as this answer recieves more votes!

Answered by ETHproductions on November 19, 2021

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[xxright]

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

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

9-vote

3xge 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!

Answered by Conor O'Brien on November 19, 2021

Hassium

Hassium is an object oriented programming language in C#. It contains many of the exact C# classes and over 400 functions built in. You can run Hassium code and examples here.

Length 1

5

This is a constant integer in Hassium.

Length 2

a:

This is a label in Hassium. Hassium supports labels and gotos as well as all types of loops.

Length 3

m()

This is a call to a function called m in Hassium.

Length 4

a=4;

This is declaring the variable a with the initial value of 4. In Hassium you don't have to declare the type of variable like int a=4;

Length 5

a=[];

This declares a new array in Hassium, where arrays are Javascript and python like. From here I could do a.add(), etc.

Length 6

use IO

This imports the IO module into the global namespace, which contains sever different classes including File, Directory, and Path. Hassium as a whole has several of these builtin modules with countless classes.

Length 7

print()

This is the most simple function in Hassium, the print() function which takes in a string and displays it to the console without a trailing newline. print() is one of the functions that is in the global namespace, and not in a class or module.

Answered by Jacob Misirian on November 19, 2021

TI-99/4 GPL byte codes

Factoid:

GPL stands for Graphics Programming Language. It is a byte-wise interpreted language that is found in GROMs in both the console and cartridges. GROMs are 6k ROMs with an internal 16-bit address counter. The upper three bits determine which GROM will respond. Most instructions can access CPU memory or video memory with ease. Which is important as the console only has 256 bytes of CPU RAM. It was introduced on the TI-99/4 in 1979 and also used on the TI-99/4A.

Note: All bytes and addresses are in hexadecimal.

Length 1:

03   ; SCAN

This will scan the keyboard and/or joysticks using the mode found in CPU byte 8374 and place the scan code in 8375. Joystick displacements may be placed in 8376 (x) and 8377 (y), depending on the mode.

Length 2:

07 20    ; ALL ' '

This will fill the first 768 (32x24) bytes of video memory with spaces. In the default video memory layout, this fills the entire screen with the given character. No provisions are made for different layouts or 40 column mode which uses 960 (40x24) bytes. The TMS9918A Video Display Processor (vdp) can place the screen on 1K boundaries and the character definitions on 2K boundaries. To maximize space for tokens and variables, BASIC places both of these overlapping at the beginning of the 16K video memory. This makes the first 96 character definitions unusable, so BASIC has a bias added to the ascii values on the screen. Provisions are made in several rom routines to accommodate this bias.

Length 3:

95 A1 23    ; DINCT V@0123

This adds 2 to video memory word 0123. A word on the TI is 2 bytes, msb first. Most instructions can operate on a byte or word, in video and/or CPU memory. For video memory addresses from 0F00 to 3FFF, the encoding takes one more byte. Address encoding can get quite involved, including indirection and indexing.

Length 4:

A0 A1 23 10    ; ADD @8310, V@0123

This adds CPU byte 8310 to video memory byte 0123. For CPU addresses 8300 to 837F, the encoding only takes 1 byte. Also, all CPU addresses have a bias of 8300 added to the encoded value. This is because the fast 256 bytes of CPU ram is at 83xx. For two operand instructions, like this, the destination is encoded first.

Length 5:

08       ; FMT
21 48 49 ; VTEX 'HI'
FB       ; FEND

This will draw the string 'HI' vertically at the current display location, stored in CPU byte 837E (row) and 837F (col). GPL has an alternate interpreter known as the format sub-interpreter. The first and last lines enter and exit the sub-interpreter, respectively. Most of the FMT commands use the lower 5 bits of the opcode as a count, 1 to 32, encoded as one less than the count.

Length 6:

30 10 A0 00 80 00    ; MOVE @8310, G@8000, V@0000

This will move the number of bytes in CPU word 8310 from GROM address 8000 to the beginning of video memory. Move is possibly the most powerful GPL command. It can use GROM address space as source or destination, in addition to using the usual address encoding. It can also use the read only video controller registers as a destination.

Length 7:

06 00 34 ; CALL BEEP
03       ; L1: SCAN
40 13    ; BR L1
0B       ; EXIT

Now we have a real program that beeps once, waits for a key, and then resets the console. TI defined several fixed entry points for GPL calls such as BEEP, which plays a 1397 Hz tone for 200 ms. SCAN was used in the length 1 snippet. It also returns the condition (cnd) bit set if a new key was detected. BR Branches to the label if the cnd bit is Reset. Individual GROMs are 6K bytes on 8K boundaries and the BR and BS (Branch if cnd is Set) instructions are limited to targets in the current GROM. Cartridges are given complete control over the console, so an EXIT resets back to the power on screen.

Length 8:

0F 17    ; COSX2: XML VPUSH
0F 0D    ; XML SMUL
06 00 2C ; CALL COS
00       ; RTN

This makes a subroutine that returns cos(x2). Where the input and output are the floating point value in CPU ram 834A. XML is eXecute Machine Language procedure. The second byte of the XML instruction defines the table (upper nibble) and index in that table (lower nibble) to get the address to execute. The first two tables (0x and 1x) are predefined in rom. VPUSH pushes the float at 834A onto the floating point stack in video memory. SMUL multiplies the float at 834A with the top of the floating point stack. COS calculates the cosine of the float at 834A (in radians). RTN returns back to the caller. The TI floating point format is 8 bytes with the first byte the exponent and the remaining 7 bytes are base 100 digits. This yields 14 decimal digits of precision. Not bad for 1979.

Length 9:

07 20                 ; ALL ' '
35 00 C0 A3 00 A2 FF  ; MOVE 192, V@02FF, V@0300

This is what is needed to clear the screen in 40 column mode as noted in the length 2 snippet. This assumes that the screen is at the beginning of the video memory. The move copies the last byte filled by ALL to the remainder of the screen. This trick to fill memory by setting the move destination one more than the source is used in the TI GROMs quite a bit. Here we see move with an immediate count showing how flexible this instruction can be. Also, note that the built-in BASIC cannot use 40 column mode because of the video memory layout mentioned in the length 2 snippet. Extended BASIC with the expansion ram can use all of the video memory for video.

Length 10:

0E C2     ; PARS >C2
83 4A     ; DNEG @834A
C6 4C 63  ; CH 99, @834C
76 71     ; BS 5671
10        ; CONT

This is an actual snippet from the built-in BASIC GROM called when an unary minus token is encountered. PARS and CONT are GPL commands that are only used by BASIC. PARS parses BASIC tokens until it reaches a token that is smaller than the value given. CONT continues the BASIC interpreter. The TI floating point format indicates a negative value by negating the first word. CPU address 834A is the current floating point value as mentioned in the length 8 snippet. CH sets the cnd bit if the destination is larger (unsigned comparison) than the source. BS jumps to GROM address 5671 to display an error message if the byte at CPU address 834C is greater than 99. This is the second base 100 digit of the floating point value. Since BASIC is written in GPL and GPL is also interpreted, the BASIC interpreter is painfully slow.

Length 11:

02 FF       ; RAND 255
BC B0 00 78 ; ST @8378, V*8300
91 00       ; DINC @8300
90 78       ; INC @8378
01          ; RTNC

This is a routine that places a random byte at video memory pointed to by CPU word 8300, increments the pointer, then returns the cnd bit set if the number was 255. RAND n puts a random number between 0 and n into CPU byte 8378. ST copies that byte to video memory. V*8300 indicates indirection into video memory, but all pointers can only be in CPU memory. DINC increments a word. INC increments a byte and sets the cnd bit if the result is zero. RTNC returns from the routine without clearing the cnd bit. Normally, calls, returns, and branches clear the cnd bit. This feature can be used to create a fixed entry point table using BR which is a byte smaller than B (unconditional branch). This was used by TI as mentioned in the length 7 snippet.

Answered by Zakipu on November 19, 2021

dc

Almost nine months later -- I can't believe dc is not on the list!

Factoid

dc (desktop calculator) is a Unix utility older than the C programming language, and also the hardest programming language to google. Luckily it's probably preinstalled on your Linux, Unix or Mac box, and available for Cygwin too!

Length 1

1

dc is a stack oriented language. 1 is an instruction that pushes the number 1 one the stack so that we can use it for other instructions.

Length 2

?f

These two characters is a whole dc program that actually does three things! It takes a line of input, evaluates the input as dc code, and prints the contents of the stack afterwards. You can feed it with the next snippet that I will post if I get another vote :)

Length 3

zzp

z pushes the current stack depth. Initially the stack is empty, so 0 is pushed on the stack. The stack is then 1 deep, so the next z pushes 1. p prints the top of the stack, which at this point is 1 (although the stack depth is now 2 :D).

Length 4

1A0F

dc supports number input to be in any base from 2 to 16, so the characters 0123456789ABCDEF all work as digits. Input numbers are not limited to only digits found in the current radix, but they still respect the positions of that base. This means that in base 10 (which is the default), the given snippet evaluates to 1*10^3 + A*10^2 + 0*10^1 + F*10^0 = 2015 :)

Length 5

O[P]x

A convoluted way of printing a newline! O pushes the current output radix (which defaults to 10 and is independent of the input radix). [] defines a macro and pushes it. x pops the macro and executes it. P pops and prints a value as a byte stream.

Length 6

[dx]dx

Duplicate and execute, duplicate and execute, rinse and repeat. One copy of the macro is always left on the stack, so this loops forever. On some systems or implementations it may crash.

Length 7

[]sf7>f

This is sort of an if-statement: It will execute the empty [macro], which is first stored in register f, if the top of the stack is less than 7. Intuitive, huh? Just wait for an if-else! I will need way more characters for that though ;)

Length 8

3812649P

Prints a smiling face :-) Another example of the P command. 3812649 is the character points of the smiley string shifted to their correct position in base 256 and added together. Very useful technique for creating quines and quine-like programs.

Length 9

[9<L]dsLx

This is kinda the standard template for a loop -- 9 can be replaced with any code, and you can use other comparisons than <. As the snippet stands now though, it is perhaps not the most useful thing in the world:

The comparison consumes one element in addition to the 9 that is pushed every time, so the snippet will pop each element down to, and including, the first element which is less than or equal to 9. If it were to empty the stack, the last comparison would fail with a warning, and leave the 9 on the stack.

Length 10

6581840dnP

If I had actually counted how few characters it takes beforehand, I guess I wouldn't have ruined the surprise just two snippets ago, but yeah... this is a quine.
(That means that the program prints out its own source code)

Length 11

I just came up with this for the dc golfing tips post, and I'm quite excited because I'm absolutely sure that this is the shortest possible way to write an if-else-statement!

Suppose you want to do if top-of-stack == (THAT) then (THEN) else (ELSE)

[[(THEN)2Q]sI(THAT)=I(ELSE)]x

Uses the I register. The placeholders (THAT), (THEN) and (ELSE) isn't part of the byte count, and = can of course be exchanged with any of >, !>, <, !<, !=.

Answered by daniero on November 19, 2021

Labyrinth

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

Factoid

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

Length 1 snippet

'

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

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

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

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

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

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

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

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

Length 2 snippet

[]

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

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

Length 3 snippet

Okay, real code now...

90.

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

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

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

90.090.090.090.090...

and so on, repeatedly printing Z.

Length 4 snippet

4!@

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

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

Length 5 snippet

I think we can spare a newline now:

?
~!@

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

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

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

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

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

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

Length 6 snippet

,)@
.(

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

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

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

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

Length 7 snippet

<.$,23>

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

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

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

.$,23><

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

<.$,23>

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

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

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

Length 8 snippet

"
:-"
~"

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

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

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

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

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

Length 9 snippet

 "
"_;
 ;

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

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

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

Length 10 snippet

_v"
 "
 )"

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

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

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

_)"
 v
 ""

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

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

Answered by Martin Ender on November 19, 2021

Casio-BASIC

Casio BASIC is very unlike TI-BASIC; firstly, it doesn't require as much RAM, memory or power. Programs typically only use a few KB of RAM. Secondly, it allows scrolling through the list of functions to write a program, or the use of special buttons which insert common characters. However, unlike TI-BASIC, functions can simply be typed in letter by letter from the keyboard.

Length 8 snippet

Print 9!

This prints 9 factorial, which is 362880.

Length 9 snippet

Print n+n

Even though we didn't define n, the calculator doesn't throw an error. Instead, it treats n as an expression, and prints out 2·n. (A floating dot is used by the calculator to represent multiplication)

Length 13 snippet

DrawGraph x^2

Opens an empty graph plane, and draws the graph of y=x^2 onto it.

Length 15 snippet

seq(x^2,x,1,10)

This will print x^2 for all values of x between 1 and 10.

Answered by galexite on November 19, 2021

Stylus

Considering CSS is in here, I might as well add this in.

Stylus is a language which is compiled in to CSS3. It's easy to use and adds many features in to the language, like nesting, variables, functions, maths, and relaxed punctuation requirements.

Length 1

=

Unlike other CSS pre-processor syntaxes, Stylus allows a variable to be named by any Unicode character that isn't a whitespace, number, or used symbol, without using the $ symbol to denote variables. CSS does not have any concept of a variable.

Length 2

p
    a

Nesting allows you to stop repeating the names of the elements, and looks much prettier and easier for a person to read.

Answered by galexite on November 19, 2021

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

Answered by ASCIIThenANSI on November 19, 2021

ChucK

Factoid

ChucK is a time-based programming language that handles sound synthesis. It has most standard functions, as well as multiple sound generators and ways to modify waveforms.

Length 2 snippet

=>

This is the ChucK symbol. It requires a "chucker" to the right of the symbol and a "chuckee" to the left. What it does depends on the syntax: If it's given an integer as the chucker and a initialized integer variable as the chuckee, it will store the integer in the variable. If it's given a sound unit as the chucker and a modifier/output as the chuckee, it will send the sound through the modifier/output.

Length 3 snippet

dur

When initializing a variable, you can make the variable type a duration by using this command. In doing so, durations in time can be stored in the variable (useful for allowing sounds to end before moving on in code).

Length 5 snippet

5::ms

This is another snippet to do with time. ms means milliseconds, and the 5 is literal. This is the format for a duration in ChucK, and can be assigned to a dur variable.

Answered by The_Basset_Hound on November 19, 2021

gs2

Factoid

gs2 is my own little golf language that has the highest average score across submissions of all languages on shinh's golf site. It uses all 256 bytes, so it's like a cross between CJam and machine code. It's not perfect, but sometimes it's really, really good.

Note: I'll encode all of the programs in CP437, as if they were printed on a DOS computer, because I don't know of any better character set that assigns a symbol to all 255 bytes. (Even this one lacks a glyph for FF. Oh well.) To the right of each snippet, you'll find a hex dump.

Length 1

f                          66

I wanted to one-up goruby's 1-byte Hello, world!, so... This prints "1n2nFizzn4nBuzzn...". :)

Length 2

ï≡                         8B F0

8B is Python's islower() function, but it also works on bytes. __ F0 is a 1-byte-block filter (it goes all the way up to __ __ __ __ __ __ F5). Thus, this program extracts all of the lowercase characters from STDIN.

Length 3

0▓B                        30 B2 42

If the first byte of a program is 30, it's in line mode -- sort of like Perl/Ruby's flags. The remainder of the program, B2 42, will get mapped over each line of input.

B2 is called counter, and the first time you push it, it's 1, the second time it's 2, etc. There's no way to reset it or anything. Dead simple.

42 is swap, which will put the counter before the lines we're looping over. Thus this will perform a very lazy kind of line numbering:

abc          1abc
defgh   ->   2defgh
gs2!         3gs2!

Answered by Lynn on November 19, 2021

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

Answered by Florrie on November 19, 2021

Burlesque

Burlesque is a stack-based, lazy, concatenative esoteric programming language. It was designed as a utility for students of computer science but it has become a language used for golfing. Since Burlesque has two character built-ins programs obviously grow twice as fast as programs in golfing languages with one character built-ins do. Burlesque is more like a command line utility tool for easy homework or related things like when you need to know what that number in base 4 is or what are the subsequences of this set or what are the permutations of this string and the like.

Burlesque has 400+ built-ins and growing. This also means that Burlesque's power stems from two main factors: The laziness and the amount of built-ins. The drawback is that the language is not very verbose and you can't infer what a code is doing by simply looking at the syntax and control structures since those don't really exist in Burlesque. The only way to understand Burlesque programs is by either looking everything up all the time or by memorizing a lot of built-ins.

Website: http://mroman.ch/burlesque/

Length 1

Cat program:

# Q
$ echo -n "123" | ./blsq --stdin "Q"

Length 2

Reverse a list:

# <-
$ ./blsq --no-stdin "{1 2 3}<-"
{3 2 1}

Length 3

Reverse STDIN:

# <-Q
$ echo -n "123" | ./blsq --stdin "<-Q"
321

Length 4

Add two numbers read from STDIN:

# ps++
$ echo "12 13" | ./blsq --stdin "ps++"
25

Length 5

Show all reversed substrings:

# su)<-
$ echo -n "1234" | ./blsq --stdin "su)<-"
{"1" "2" "3" "4" "21" "32" "43" "321" "432" "4321"}

Length 6

Read integer from STDIN and calculate sum[1..N]:

# riro++
$ echo -n "5" | ./blsq --stdin "riro++"
15

Length 7

Read integer from STDIN and calculate 10^n:

# ri10j^?
$ echo -n "5" | ./blsq --stdin "ri10j?^"
100000

Length 8

Repeat a line from STDIN length(line) times (trailing newline required):

# ~]sa.*uN
$ echo "abcd" | blsq --stdin "~]sa.*uN"
abcd
abcd
abcd
abcd
$ echo "abc" | blsq --stdin "~]sa.*uN"
abc
abc
abc

Length 9

Chance that we have exactly 0 successes within 8 tries where p=0.1 (binomial distribution):

blsq ) 8 0.1 0Bp
0.4304672100000001

Length 10

Convert from RGB to hex (challenge on codegolf):

blsq ) "72 61 139"psb6['#+]
"#483d8b"

Answered by mroman on November 19, 2021

jq

Factoid

jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.

Length 0

With an empty code jq just formats the JSON data. Often an essential first step when you need to process a huge .json file:

bash-4.3$ jq '' <<< '{"network":"StackExchange","site":["Programming Puzzles","Code Golf"]}'
{
  "network": "StackExchange",
  "site": [
    "Programming Puzzles",
    "Code Golf"
  ]
}

Length 1

.

The . is the simplest filter, kind of neutral: just the unaltered input (kind of cat). But more important, is the way to refer the current value (kind of $_) in an expression:

bash-4.3$ jq '.*2' <<< '3.14 42 2015'
6.28
84
4030

bash-4.3$ jq -R '{(.+"-"+.):.}' <<< 'foo'
{
  "foo-foo": "foo"
}

Length 2

[]

No, not those [ and ] which delimit an array literal in JavaScript, Ruby, PHP, … (Though that syntax is also valid in jq.) Here [] is more like Ruby's splat operator, which flattens an array:

bash-4.3$ jq '.|"(.) Mississippi"' <<< '["one","two","three"]'
"["one","two","three"] Mississippi"

bash-4.3$ jq '.[]|"(.) Mississippi"' <<< '["one","two","three"]'
"one Mississippi"
"two Mississippi"
"three Mississippi"

The difference may be more clear if we use concatenation instead of interpolation:

bash-4.3$ jq '.+" Mississippi"' <<< '["one","two","three"]'
jq: error (at <stdin>:1): array (["one","two...) and string (" Mississippi") cannot be added

bash-4.3$ jq '.[]+" Mississippi"' <<< '["one","two","three"]'
"one Mississippi"
"two Mississippi"
"three Mississippi"

Length 3

add

No, not the plain old addition. That is the same + in jq too. add is a builtin function which adds all elements of an array:

bash-4.3$ jq 'add' <<< '[1,3,5,7,9,11,13,17,19]'
85

To solve Gauss's task of adding numbers between 1 and 100:

bash-4.3$ jq -n '[range(1;101)]|add'
5050

But as it is just repeated +, works for any data type for which + is defined, for example strings, which get concatenated:

bash-4.3$ jq 'add' <<< '["stack","over","flow"]'
"stackoverflow"

Length 4

type

Just tells what type the data has:

bash-4.3$ jq 'type' <<< '3.14 "3.14" [3.14] {"pi":3.14}'
"number"
"string"
"array"
"object"

Of course, in most cases this will be used in some kind of condition when iterating over an array's elements. For example to find out which one is not numeric:

bash-4.3$ jq '.[]|select(type!="number")' <<< '[0,1,2,"cukoo´s egg",4,5]'
"cukoo´s egg"

Length 5

empty

null means nothing, the absence of something.
empty means absolutely nothing, not even nothing.

bash-4.3$ jq '.[]|if.==2then null else. end' <<< '[1,2,3]'
1
null
3

bash-4.3$ jq '.[]|if.==2then empty else. end' <<< '[1,2,3]'
1
3

Answered by manatwork on November 19, 2021

HAML (HTML Abstraction Markup Language

Factoid

Haml (HTML abstraction markup language) is based on one primary principle: markup should be beautiful. It’s not just beauty for beauty’s sake either; Haml accelerates and simplifies template creation down to veritable haiku.

I'm partly doing this because I'm interested to see how many votes this could get around half a year after the original post ;)

Length 1 Snippet

%

% is the tag marker for Haml. So if for example %div was used, it would result in <div></div>

Length 2 Snippet

%a

As said above, % is the tag marker for Haml. So the a following the tag would tell Haml that it needs to create a set of tags with a inside like this: <a></a>. The <a> tag defines a hyperlink, which links pages and/or objects together.

Length 3 Snippet

%td

As above, this would form the tags for a table cell - <td></td>. Table Cells need to be prefaced by: 1) a Table tag <table>, 2) The Table Body (this is optional) <tbody>, 3) a Table Row <tr>. You would end up with something like this:

<table>
  <tbody>
    <tr>
      <td>[Content Here]</td>
    </tr>
  </tbody>
</table>

Length 4 Snippet

.a I

As <div> tags are so common, you can leave them off in Haml. The . here indicates that the text that follows will be the CSS Class to apply, then the text after that is placed inside the div. So the above would be:

<div class="a">I</div>

Length 5 snippet

.a#bc

A . defines the CSS Class - as above - but the new feature here is the #. This defines the CSS ID of the element. So the above would equal:

<div class="a" id="bc"></div>

Length 6 Snippet

.a Hi!

The second snippet that actually shows something!

Any plain text that comes after a class or id etc is the content for the tag. So the above code would result in:

<div class="a">Hi!</div>

Length 7 Snippet

%ul %li

Lists! The above is an unordered list (%ul) and then the list items are each specified as %li. So for the above to show something, we could do the following.

%ul %li Number one! %li And Two!

This would result in:

<ul>
    <li>Number One!</li>
    <li>And Two!</li>
</ul>

Length 8 Snippet

%p.a#b c

A paragraph! As before, the % indicates a HTML tag, so the above would be:

<p class="a" id="b">c</p>

A saving of 17 characters - 68% reduction :)

Length 9 Snippet

#a .b.c D

A . is the prefix for a css class, and to join two classes together, simply put the two classes without a space like above - .b.c. So the above equals

<div id="a">
  <div class="b c">
    D
  </div>
</div>

Length 10 Snippet

:style=>""

To insert custom CSS to an element in html, you would generally use style="<!-- css here -->". The Haml variant is as above. You would use it as below:

%p{:style => "color: #fff;"} A Paragraph

Converted to HTML is becomes

<p style="color: #fff;">A Paragraph</p>

Answered by CalvT on November 19, 2021

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.

Answered by CJ Dennis on November 19, 2021

Clojure

Clojure is a variant of Lisp which runs on the Java virtual machine and the .Net virtual machine. A cross-compiler is also available which will turn Clojure code into JavaScript, and thus Clojure code can be run on just about any computer. Clojure can be written in a functional style which is what got me interested in it.

Length 1 Snippet

; - comments begin with a semi-colon and run until the end-of-line. This is also a valid (if not particularly interesting :-) one-character program.

Length 2 Snippet

One of the strengths of any Lisp-style language is its built-in support for collections. In Clojure there are three main collection types:

  • Lists, which are groups of values surrounded by parentheses - ()
  • Vectors, which are groups of values surrounded by square braces - []
  • Maps, which are pairs of values surrounded by curly braces - {}

Lists are both a data structure and the basis for all programming because all programs in Clojure consist of Lists of function names and arguments (Lisp was originally an acronym which stood for List Processor). An empty List (()), Vector ([]), or Map ({}) is also a valid (if uninteresting) program.

Length 3 Snippet

Invoking a function in Clojure is done by putting the function name first in a list (also known as a sequence), followed by its arguments. For example, if we have a function named a then we would invoke it as (a), assuming it takes no arguments.

Length 4 Snippet

@user100464's comment got me thinking about quoted forms. A quoted form is introduced with a back-quote character, so

`(a)

is a quoted form which will invoke the function a when the quoted form is executed. (This can also be written as (quote (a))). According to this blog posting by Colin Jones, quoting is "one of the most Lispy of the Lisp features". Colin's blog post goes into a good amount of detail about using quoting in Clojure macro definitions (which IMO is a topic worthy of entire books) - however, let's simply say that you can evaluate a quoted form using the (you guessed it) eval function. So let's say we create a simple function a with

(defn a [] (println "a invoked"))

which we can invoke from the REPL with the "normal" unquoted form

(a)

which prints

a invoked

Cool. Now let's create a quoted form which will execute our function a:

(def quota `(a))

We can then invoke it with

(eval quota)

which prints

a invoked

So at its most basic level quoting allows us to create a form to invoke a function, then keep that form hanging around uninvoked until we want to invoke it. For those familiar with C a quoted form is a bit like a function pointer, allowing you to save up the ability to invoke a function anonymously until you're ready to do so. (Lispers - please don't start in on me. Yes, I know what I just said is hideously inaccurate and nearly-but-not-quite completely wrong. However, it's "lies to children" (ref. Terry Pratchett et al in his "Science of Discworld" series). If you think explaining nuclear physics to wizards is easy, you try it! :-) ((Rant on) And C'ers - please don't take offense. I wrote C et se derivees on a daily basis for over 10 years, Back In The Day. I don't anymore. Why? Simple - Moore's Law won. Due to CPU speed increases execution time has become a DRM issue - i.e. whether a compiled-and-optimized C program takes 0.0001 seconds to execute vs. an ugly, slow interpreted language version of the same program taking 0.1 seconds to execute Doesn't Really Matter - the user pushes Enter and the answer comes out before their finger lifts off the key. My day job is writing boring back-office code for a major retailer using Oracle's PL/SQL language (think "Ada with embedded SQL"). The byte-code interpreter is pretty good - but execution time is absolutely dominated by SQL execution time Every Single Time, so it's not that the PL/SQL byte-code interpreter is so great, it's that the CPU is sufficiently fast and the database is so much the elephant in the room that faster execution of non-database code Doesn't Really Matter. (Rant off) :-).

Length 5 Snippet

An example of invoking a function f with a single argument 1 would look like

(f 1)

Length 6 Snippet

Length 7 Snippet

(recur)

Ooooh! Tail recursion! Oooooh!

OK, now that we've gotten over that - WHAT THE HECK IS TAIL RECURSION?!?!? And I don't actually HAVE a tail - can I still use it?!?

Yes - yes, you can.

Tail recursion is a nice way of saying "Branching back to the start of the function (or some other point) instead of making a time-and-memory-consuming recursive function call". Recursive function calls do nasty things like consuming stack space, which is in limited supply and when it's gone, so's your program.

And oh-by-the-way, in Clojure you have to use tail recursion if you want to do any kind of looping. It's just kind of what you do.

Tail recursion in Clojure is done by using the recur form, which takes a variable number of values (see the Length 11 Snippet below for more information), binds those values to the bindings at the recursion point (say what?!?), and then jumps back to the recursion point. And oh-by-the-way - (recur) must be in tail position. (HUH?!?!?).

OK, let's explain.

First, what's a recursion point? A recursion point is a point in the program you can recurse back to. (Oh, thanks...). No, seriously - there are only two recursion points in Clojure - either the beginning of a function (in other words a (defn... or (fn... form) or the top of a loop (i.e. the (loop... form).

So, why all this agony to do looping? Why not something like (for (= i 0) (<= i 10) (+ i 1))? Recall if you will that, in general, "variables" in Clojure DON'T CHANGE - in other words, variables are really constants. (Clojure cognoscenti: "lies to children", OK?). Thus, you don't (usually) assign a new value to a "variable", and thus you can't do the usual "loop" thing where you change the value of the loop control variable.

So what you do in Clojure is, you re-bind the function-or-loop parameters to new values, then re-run the function-or-loop against those new values. Hopefully, since you're doing recursion (and nobody likes an infinite recurser :-) you've got something in the body of your recursive code which forces the recursion to terminate. If not - well, then you can use your CPU to grill hot dogs... :-)

And, oh yeah - "tail position". There's a really good explanation of it here, but suffice to say that an expression is in tail position if it would be returned from the form - i.e. it's not followed by any other form executions.

Now, in some Lisps tail recursion is performed by executing a form which calls the function the code is currently in. The compiler recognizes this and turns the call into a tail-recursive branch back to the beginning of the function if it can - so you'd see something like

(defn some-func [n]
  (if (< n 10)
    (do                       ; then case
      (printf "loop continues %dn" n)
      (some-func (inc n)))
    (printf "loop donen")))  ; else case

where (some-func (inc n)) would be a tail-recursive invocation of some-func.

The problem is that if the recursive form invocation isn't truly in tail position it will still be compiled properly by the compiler (it's valid code, after all) - but it will become a stack-consuming function call, which can cause your program to blow up unexpectedly, and it can be very difficult to figure out what's gone wrong.

Clojure's solution is to use the special recur form to indicate that a tail-recursive loop is desired. The compiler checks to ensure that the recur form is in tail position - i.e. that there are no form invocations which follow it in the loop - and then generates to code to re-bind arguments and branch back to the recursion point. In this manner you're guaranteed to get a truly tail-recursive branch or else you get a compiler error. Thus, in Clojure some-func would be:

(defn some-func [n]
  (if (< n 10)
    (do                       ; then case
      (printf "loop continues %dn" n)
      (recur (inc n)))
    (printf "loop donen")))  ; else case

For other examples of the use of (recur) look a bit further down the page to the Length 11 Snippet.

Length 8 Snippet

Length 9 Snippet

Length 10 Snippet

Length 11 Snippet

(sum 1 2 3)

One of the things I like about Clojure is its handling of variable numbers of parameters to a function. Let's say that you want to write a function named sum to sum up a bunch of numbers (which is a completely stupid thing to do in Clojure, as it already has a very nice function called + which does exactly that - so (+ 1 2) returns 3, (+ 1 2 3 4) returns 10, and so on - but we'll do it anyways, not because we're stupid, but because we're writing a snippet to explain a concept :-). Well, golly, you say, if I want to enter (sum 1 2), that's a function which takes two arguments; but if I want to add up three arguments that would be (sum 1 2 3), which would be a different function; and then (sum 1 2 3 4 5 6 7 8 987654321) would be Yet Another Function, etc, ad nauseum. It sure would be nice if there was a way to let a function just take in all the arguments someone wanted to pass, without having to explicitly name them every time. And, of course, there is... :-)

In Clojure you specify a function which takes a variable number of parameters thusly:

(defn a-func [arg1 arg2 & more-args] ... )

This function requires two arguments arg1 and arg2, and accepts an undefined number of additional arguments which are put into a vector and bound to the argument more-args. So let's see how we'd take advantage of this to write a sum function:

(defn sum [n & more-n]
  (loop [ tot     0
          num     n
          rest-n  more-n ]
  (if (> (count rest-n) 0)
    (recur (+ tot num) (first rest-n) (rest rest-n))
    (+ tot num))))

Here we define a function sum which takes at least one argument, named n, and optionally takes a bunch of other arguments which will be lumped together into more-n. Inside the function we create a loop (which is, if you recall, a recursion point) which defines several bindings: tot is the summed total of all the arguments, which will be returned later; 'num', which is the number we're working with right now; and rest-n which is the rest of our numbers.

Note that a slightly more Lisp-y way to define our sum function is to use a "worker" function to do all the actual summation work instead of a loop:

(defn sum-all [tot n more-n]
  (if (> (count more-n) 0)
    (recur (+ tot n) (first more-n) (rest more-n))
    (+ tot n)))

(defn sum [n & more-n]
  (sum-all 0 n more-n))

This version turns the loop of the first version into a separate function, which then recursively re-invokes itself.

So now you know a bit about handling variable numbers of arguments in Clojure.


(Trying to make snippets for a rather verbose language like Clojure is relatively difficult. To quote AC/DC, "I'll tell you, folks, it's harder than it looks...") (And no, I'm not going to play the bagpipes :-)

Answered by Bob Jarvis - Reinstate Monica on November 19, 2021

Microscript

Microscript is a new expiremental golfing language I've been working on recently. For my Death By Shock Probe challenge, I was able to write a program that would have beaten out the leading Pyth entry by one byte, except for the fact that the language is too new to be eligible to actually compete in that challenge.

It uses a pair of stacks to manipulate data, and currently has just over 30 distinct commands

The esolangs wiki article can be found here

Length 0 snippet:

The empty program prints 0, followed by a newline. This is because the main register is initially 0, and printing is implicit unless otherwise specified.

Length 1 snippet: p

Prints the contents of the register to the output, followed by a newline. On end of execution, this will be done automatically, unless execution was halted by the h command.

Length 2 snippet: 99

Any positive integer literal not part of another command will increment the main register by that value. Thus, unless part of another command, this will add 99 to the value in said register.

Length 3 snippet: is*

Currently the shortest example program on the esolangs wiki article. Takes in an input and squares it. i takes a number from the input and writes it to the register, s pushes it to the stack (unlike in HSPAL, this does not zero the register), and * pops it off the stack again and multiplies it by the value in the register, writing the result to the register. Then, as mentioned above, the new value is printed implicitly.

Length 4 snippet: isi+

Another example program from the esolangs wiki article. Takes two inputs and outputs their sum.

Length 5 snippet: '~Pph

'<any character> is the language's equivalent of a character literal. P prints as a character while p prints as an integer. Finally, h halts immediately without the implicit printing. Therefore, the output from this is ~126. This is technically equivalent to the shorter (3 byte) '~P.

Length 6 Snippet: i{z1p}

This is a truth machine which converts values not in {0,1} to 1. The closing bracket is optional in this case, but I already had a length 5 snippet. {} is the equivelent of BrainF***'s []; Microscript uses square brackets for other purposes.

Length 7 Snippet: 20ec1r4

Simulates the rolling of 1,048,576 four-sided dice. This is what would have been the winning entry for my afformentioned Death By Shock Probe challenge had Microscript come out a short time earlier. The c command was the language's first form of iteration- essentially "zero the register, then repeat the following a number of times equalling the value that was in the register before it was zeroed". 1 increments by 1, and r4 increments by a random integer on [0,4). Lastly, e is a base-2 exponential function while E is the base-10 equivalent. Thus, 10Ec1r4 (or, equivalently, 1EEc1r4) would simulate the rolling of ten billion four-sided dice. Eventually.

Length 9 snippet: 1{I[h]fan

A cat program that terminates on the first empty line (as the language currently lacks EOF detection)

Length 11 snippet: 0"Caxq"Caxq

A reverse quine, and it's even one byte shorter than the one in the esolang article

Length 13 snippet: ic1s]z1{[ph]*

Calculates the factorial of a number given as input. Limited by the language's 64-bit integer type.

Answered by SuperJedi224 on November 19, 2021

GolfScript

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

Factoid

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

1 character

,

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

2 characters

~~

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

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

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

3 characters

-1%

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

4 characters

{+}*

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

    [a b c d e] {∘} *

==  a b ∘ c ∘ d ∘ e ∘

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

5 characters

2base

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

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

6 characters

n/.&n*

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

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

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

7 characters

{,}$-1=

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

8 characters

":n`":n`

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

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

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

9 characters

"#{size}"

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

10 characters

{9(:9.(}do

This prints:

87654321

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

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

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

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

Answered by Lynn on November 19, 2021

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.

Answered by NinjaBearMonkey on November 19, 2021

Element

This is a language that I invented in early 2012 to be a simple golfing language. By this, I mean that there is very little to no operator overloading. The operators are also simpler and fewer in number (all single characters) than most modern golfing languages.

You can find the current version of the Element interpreter, written in Perl, right here.

The most interesting features of this language are its data structures. There are two stacks and a hash that are used to store information. One stack is used mainly for arithmetic, while the other is used mainly for logic. The hash is used to store "variables." The use of a hash means that the number of variables can be practically unbounded.


Length 1 Snippet

#

The # operator removes and destroys a single item from the top of the main stack (the m-stack or arithmetic stack). When standing alone, this doesn't do anything at all.


Length 2 Snippet

_`

This is a "cat" program, or a program that outputs its input. The _ operator gets a line from STDIN and puts it on the main stack. The ` operator (a backtick) removes the top item from the main stack and prints it to STDOUT.


Length 3 Snippet

!{}

This program is an infinite loop. The ! is a logical NOT. The control stack starts empty, logically equivalent to "false," so we must invert it and put a 1 on it. The {} form a while loop. It repeats as long as the top value of the control stack is true (non-zero and non-empty-string). Since the control stack will always have a 1 on top, this repeats forever.


Length 4 Snippet

_2^`

This is a program that squares the input and prints the result. The ^ is a operator which performs exponentiation. Since this is stack-based, the 2 must be pushed on the stack before the ^ is performed. The ^ is just one of the many basic arithmetic operations possible, such as addition or modulo. All arithmetic takes place on the main stack.


Length 5 Snippet

_'[_]

This code reads a line with a number as input and then reads that number of additional lines. This can useful in some golf challenges.

The square brackets form a FOR block, which also doubles to serve as the language's IF block. FOR blocks look at the top value on the control stack and repeat the code inside that number of times. The first line of input is transferred to the control stack with '. Element can be rather heavy with the apostrophes/quotation marks/backticks sometimes.


Length 7 Snippet

_,1+,#`

This takes a character from input and outputs the character with the character code 1 greater than that. It's like a ROT1 cipher without the rotation. The , is the char<->code operator, which pushes both the number and code value for its input. The first occurrence is used to convert to a number, of the second output is used. IN the second occurrence, the number is discarded with # and the character is outputed.


Length 12 Snippet

1_'[3:~2@+]`

This prints the Nth Fibonacci number. New commands here are :, ~, and @. The : operator creates copies of the top item on the main stack. It's top argument, the 3 in this example, determines the number of copies. So, 0: is the same as #, 1: is a co=op, 2: makes one additional copy for a total of 2, etc.

The ~ is variable reading. Given a string (which can also be a number) as an argument, it returns the value that was previously stored in that variable. In this example, we are reading from a variable (the number we just made copies of) that we never stored anything in. This gives the empty string, which serves as one argument for the next operator. If we simply replaced ~ with 0, then we would have to insert a space between the 0 and the 2.

The @ is stack manipulation. Element only has one operator for rearranging the order of stuff within the stack (as opposed to moving things between stacks, which are ' and "). The first (bottom) argument of @ is the source index, and the second argument is the destination index. In this program, the arguments are 0 (represented by the empty string) and 2, so this operator consumes those numbers, and then moves the 1st thing in the stack to be the 3rd thing in the stack.

1                  push a 1
 _'                take input then move it to the control stack
   [      ]        FOR loop
   [3:    ]        make two additional copies of the top number (3 is the total count)
   [  ~   ]        turn one copy into a zero
   [   2@ ]        move from position 0 to position 2, behind the old number
   [     +]        add the old and newer number
           `       output the result 

Answered by PhiNotPi on November 19, 2021

The Hexadecimal Stacking Pseudo-Assembly Language

Alright, this is one of the several languages I've designed myself, and one of the only two three that has been implemented thus far. The program is represented as a list of 6-digit base-16 unsigned integers. Line breaks between them are optional, but not required. All other whitespace is forbidden.

It is intended to resemble a form of bytecode, even though, in reality, it isn't one. Its lack of readability may well make it a Turing Tarpit, despite the fact that it has more features than most Turing Tarpits.

Edit: It has been suggested that I score each hexit/nybble as half a byte. I think this is reasonable, so I'll go with it.

Therefore:

Length 1 snippet: 11

A command that takes a number from input. Another four hexits are required to make it syntactically valid, the next two provide a stack address and the last two are ignored.

Length 3 snippet: 110000

Takes a number from the input and pushes it to stack 00, the last two hexits are ignored but are required for the command to be syntactically valid.

Length 6 snippet: 400000400100

Pushes a zero to stack 00, and then another zero to 01. When using the first two stacks as a tape (and the third for scratch work) this is how you would initialize it at the beginning of the program, pushing a zero to stack 00, then another zero to stack 01.

Length 9 snippet: 200001400000210000

In the Brainf*** equivalence described in the documentation, this is the substitution given for the + instruction. It creates the constant 1, pushes it to stack 00, then pops the top two values of stack 00 and pushes their sum.

+, ., and , have the three shortest substitutions given.

Answered by SuperJedi224 on November 19, 2021

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

Answered by ASCIIThenANSI on November 19, 2021

Clip

Factoid

The empty program in Clip copies its input to the output (i.e. the cat program). This is because an incomplete expression takes the missing part as a string from stdin. Here, the whole thing is missing, so that is used. Each program just prints the result of an expression, here a simple string.

Length 1 snippet

A

I've seen obsolete features, but this... A is a supplier which returns the alphabet in upper case. This therefore outputs it.

Length 2 snippet

1A

If you have more than one expression at the root, only the first is evaluated and printed. Therefore, this program prints 1.

Length 3 snippet

{`

Lists use the syntax {elem1elem2..elemn<backtick> (can't actually put a backtick there for formatting issues). There is no separator, as Clip can figure out how many expressions there are. The reason for this weird syntax is that { initialises a ListBuilder, which consumes all expressions it receives and shoves them on its list. Backticks escape things, for example +<backtick> is the plus function in a format that can pass it to other functions. However, ListBuilders happen to become a list when escaped, so that's what happens.

Finally, the function converts a list to a human-readable string i.e. {1 2 3 4 5<backtick> becomes {1, 2, 3, 4, 5} instead of the default 12345. The output of my length 3 snippet is not {}, however, as the default formatting for empty lists is as strings (lists of numbers with ischar: true). It is therefore "".

Length 4 snippet

bW42

W is a supplier that always returns 2 (this allows for no spaces between 2 and 42 here; just 242 would be interpreted as the number 242). bxy supposedly converts y to base x and returns a list of digits. So, what should this snippet return? 101010, for 42 in base 2. But it actually returns 21010. I don't know why, but that is not base 2. If you replace the 2 with 10, however, this function will always give the right answer (because in base x, 10 = x).

Edit: Turns out this was a bug in the v2 interpreter I was using; v5 seems to handle it correctly and print 101010.

Length 5 snippet

"..."

You expect this to print ... (though the second quote would be unneeded), but . is Clip's escape character - like most languages' . If you imagine this as "\", it becomes clearer that the first escape escapes the second to make a literal ., and the last escape escapes the second quote to make it literally ". There is no closing quote, as these are unneeded, so this snippet prints .".

Answered by bcsb1001 on November 19, 2021

Python 3

Factoid
Python 3 has many major syntax changes from Python 2. Because of this, Python 3 is not always directly backwards-compatible with Python 2 (although a couple of edits could make it that way). Currently, Python 3 is at version 3.4. I will be using this version.
1-length code
1
Numbers above 0 and strings containing characters themselves count as True.
2-length code
''
This is the empty string. It counts as False.
3-length code
l=3
This assigns the variable l with the value 3.
4-length code
1+45
If you're running this in Python's interactive shell, you'll get 46. Why? Because in Python's shell, doing math will automatically print it. Don't believe me? Install and run Python 3 without a file, then type the snippet.
Length 5
l=[1]
This is a list with one item - 1. That's all you need to make a list - but there are some other ways.

Answered by ASCIIThenANSI on November 19, 2021

ActionScript 3

Factoid

AS3 is a scripting language designed to be used in client games and applications. It's a fully object oriented language that features dynamic objects that can be changed at run time, just like JavaScript.

1-length code

7

Each number in AS3 is treated as an object.

2-length code

as

AS3 is a strongly typed language; this is how to perform casting.

3-length code

int

This is one of the two number types that AS3 contains. The designers of the language preferred to make it simple and included just two types:

  • 64-bit float for long values and floating points.
  • 32-bit int for integers, perhaps for performance.

5-length code

a:*=1

In AS3, functions may have optional values; in this code snippet, 1 is assigned to a if no other value been passed to the function. The value after the : represents the type of a; in this case it's *, which means it can have any value. The difference between * and object is that * can also have undefined type. This is how Adobe explains it:

When you want to defer type checking to runtime, you can use an untyped property or expression to circumvent compile-time type checking in strict mode. Note, however, that runtime type checking of assignment statements occurs whether you use strict mode or not.

9-length-ish code

trace("a",0)

trace is the best logging mechanism ever! You don't need to care about the type you are passing to the trace not the number of the params, it will simply print it all back to you, separated with a space char.

Answered by Ilya Gazman on November 19, 2021

Joe

Factoid

Joe is a language I've been working on for some time. It was designed to make list mappings and interactions with functions and other lists implicit and powerful.

Length 1

In Joe, the result of the last expression of every line that isn't a function, is printed. Thus, the following program prints 1 and exits. Note: the code is indented by 3, output by 0.

   1
1

Length 2

Functions can take one or two arguments. If called with one argument, the argument appears on the right side of the function. Monadic R gives range from 0 to y, excluding.

   R5
0 1 2 3 4

Length 3

If a function is called with two arguments, they surround the function. Here we call R with arguments 2 and 7. Dyadic R gives range from x to y, inclusive.

   2R7
2 3 4 5 6 7
   7R2
7 6 5 4 3 2

Length 4

Joe does have higher-order functions, but they cannot be defined by the user. Not that you would want to.

:/>c

Here, >c ("greater choose") is a function that returns the greater one of it's parameters (1>c4 returns 4). / takes it and returns a function that applies the >c between the items of it's arguments (think of rfold1). So, />c is a max function! : then saves it to name F. Let's test this out.

   F1 2 3
3
   F1 3 2
3

Length 5

Joe has some handy ways to control data flow. Let's see one of them.

   O$rMH"Shelly""Leo""Mike"
Leo
Mike
Shelly

   O$rME"Shelly""Leo""Mike"
Mike
Leo
Shelly

Here you see two versions of a simple sorting function O$rM<rule>. The rule can basically be replaced by any function you want to. I'll use the H-rule (head) in the following explanation, which shows the steps taken to achieve this result.

To get the first letters from the strings for the sorting, we map head to them.

   MH"Shelly""Leo""Mike"
SLM

We then want to pass this as the left parameter to the sorting function O and the original list as the right parameter. We can do this using tacit composition (you can find more on the matter in Joe's quick reference).

   {MHOA)"Shelly""Leo""Mike"
Leo
Mike
Shelly

Because this is so common pattern, I've created a shorthand $r for it. O$rMH is equal to {MHOA).

Length 6

Function composition is vital in Joe. It is the only way to create any kind of data flow. See, for example, a factorial function.

/*-l1R

How does it work? The arguments are always passed to the rightmost function, from where they're cascaded back in the chain. 1R gives a list from 1 to the argument (inclusive). -l removes all zeroes ("minus list"). This allows the function to work correctly when passed a zero. Lastly, /* multiplies all values together to create the result. Now, at this point the implicit looping capabilities of Joe start to pop in. Observe.

   F:/*-l1R
   F5
120
   FR10
1 1 2 6 24 120 720 5040 40320 362880

Note: the function definition could be inlined and left unassigned.

Edit: Joe received backwards uncompatible update. All examples updated.

Answered by seequ on November 19, 2021

MUMPS

Factiod

MUMPS, or M or Cache, was a programming language created at the Massachusetts General Hospital. In fact, that's where the name come from. No, it doesn't come from an infectious disease. The name is an acronym--Massachusetts General Hospital Utility Multi-Programming System.

One interesting piece about MUMPS is that there is no restriction on language specific keywords. Couple this with the fact that whitespace is somewhat important and you can easily make some big goofs in code.

1 Character

Q

In MUMPS, it is possible to shorten most keywords down to a single letter. For instance, the Q command is short for quit and will terminate the program.

2 Characters

$H

$H will help you get the current time. This command returns the number of days since 31-DEC-1840 followed by a comma, followed by the number of seconds since midnight. So, calling $H at 5pm on 13-MAR-2015 would return 633624,61200

3 Characters

N Q

Now, this will be interesting. At first glance, you would recognize the Q command from before. However, this is where MUMPS can break, easily. The N command is short for new and is used to initialize variables. Since all data in MUMPS is technically strings, no data types are needed. However, there are no reserved keywords, so we now have a variable called Q.

4 Characters

W @Q

Now life is getting even more interesting. Let's set up the environment a little. First, you need to know that W is short for write. Think print and you're good. So, we have some variables defined as below:

N Q,A
S Q="A"
S A="B"

Now, if we take the line above in our example, what do we write out? At first thought, maybe the answer is A. That would be wrong. The answer is B. That's because the @ symbol is used for indirection, which allows you to reference variables by the name stored in a different variable. This is similar to reflection.

5 Characters

2+3*9

Now, in any normal programming language, the expression above would evaluate to 29. However, MUMPS is strictly left-to-right. This means that the expression above would evaluate to 45. Liberal use of parentheses is recommended.

Answered by tfitzger on November 19, 2021

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 

Answered by DLosc on November 19, 2021

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.

Answered by Alex A. on November 19, 2021

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!

Answered by BobTheAwesome on November 19, 2021

Tcl

See also this answer.

Factoid

In Tcl eval is not evil in most cases. And you can implement your own control structures using eval.

Length 1

h

If you run tclsh interactively, you need only to write the initial characters of a command, if it is not ambiguous. In this case, there is only one command history beginning with h. So it will print the command history, which is like this:

     1  h

If you try a instead, it will print something like this:

ambiguous command name "a": after append apply array auto_execok auto_import auto_load auto_load_index auto_qualify

Length 2

[]

It's the empty string, just like "" and {}, but works differently. It executes the commands in the brackets, which are nothing, and substitute the result of the last command, which is empty.

The empty string is also a prefix of every command. So if you type [] directly in tclsh, you can get a list of all available commands while it complains that the empty string is ambiguous.

Length 3

end

Used in lindex, lrange, string index, string range, etc. While most languages require an extra operation to get the length of a string/list to specify a position at the end of the string, Tcl simply uses end. You can also use end-k where k is an integer, to make it more useful.

Length 4

"{"

The string {. You can also use "{", but that will cause you some trouble. The bodies of control structures in Tcl are parsed as strings, and the closing brace in the following code:

if 1 {puts "{"}

will match the opening brace in the "{". So this code is an incomplete statement. You have to add another } to end the if statement.

You can escape the { to get rid of this problem. But of course, if your braces in the string are matched, you don't have to do anything. You can also make braces in different strings matched, which is still valid but may make the code less maintainable.

Length 5

{a b}

A list. Or just a whitespace-separated string. In case an element contains whitespaces or other special characters, they could be quoted using {} (which cannot contain unbalanced braces) or "" (for whitespaces) or escaped using . "" and can be combined together.

There are many commands working with lists. Basic ones are list, to generate a list from elements, and lindex, to get an element from a list.

Length 6

{{}}

Well, I can't think of a good one with length 6. So here is something random. Apparently Tcl checks only the first character in a word to decide whether it is the beginning of a {} quoted string. So you only have to escape the first { if it is not. Better also escape a matching } to make it matched for the reason described in the length 4 snippet.

Length 7

$a(a b)

Tcl also supports arrays, which are faster for random access than lists. The grammar for accessing an array is $name(index). So there isn't such a thing as multidimensional array. What would you do if you need it to be multidimensional? Well, one way is to use a list as its index, as shown in this example. Note that the braces in {a b} are quotes of a string and not a part of the list itself, which are not used in the array access grammar. And make sure the list is in the canonical form generated using the list command if you do it this way.

It's not only for array indices. Variable names and even procedure names could also contain spaces or be empty.

After writing this I realized that it isn't as perfect as I thought. Normal variable names cannot both contain any ( and end with a ). And array names cannot contain any (. It's also a bit more difficult to access a variable with } in its name, or an array with special characters in its name and also use lists as its index.

Length 8

if 0 [a]

a is executed before the if condition. If the condition is true, the result of a is parsed as commands and executed afterward. But a is always executed. I think I saw this used some times in the old underhanded or popcon questions.

Answered by jimmy23013 on November 19, 2021

Axe Parser (Ti-83/84)

Axe is an extremely low level and loose syntax third party programming language for the ti83/84+ (z80) graphing calculators. Albeit its name, programs are compiled into z80 and not interpreted. Programs are usually written in the default ti-basic editor, so code is messured in tokens. Someting like "L6" or "End" take up only one byte, despite being more then one characters long.

Site, Doc/tutorial (outdated), and commands list for my convince. I've not used the language since I got a laptop and learned Java. I'm not big into axe so please leave a comment for something cool or edit the answer if I've not touched it in a while.

Factoid If your source isn't 'archived' or backed up, a crash will delete it along with the rest of the ram such as all your basic programs you actually use for class.

Length 1:

.

A comment. Placed on the first line of a program file it will cause an error in ti-basic. To the Axe compiler (a calculator 'application') and Axe aware shells, it means that the program (the only kind of file you can edit on the calculator) is an Axe source file. Characters that follow the . until a space are the name of the compiled program or application. After the space comes an optional description of the program that some shells will show. In the basic editor, the text of some basic tokens will now be changed to Axe commands if the 'help' option was enabled in the compiler application.

Length 2:

L6

A single token and Pointer to a 768 bytes block of memory that is "highly volatile". Drawing to the buffer will corrupt it. An experienced user will be able to use the L6 token to draw directly to the buffer, bypassing the drawing commands. It is NOT the ti-basic data token and has no relation to a basic list. When the programs ends it won't even be accessible like with basic variables. L1-5 also point to special free spaces of different sizes that are much more usable. Feel free to fill them up.

Length 3:

End

Ends a block of code. Unlike in Basic, every If needs an End because Then is not used.

Length 4:

→A→B

Store multiple values at once. Ans is implied. Could be 0→A→B. This is actually optimized compared to 0→A:0→B. 0→A+2→B also works and is optimized when 1 or 2 is added. The documentation provides many optimizations. In my experience they don't matter but I never pushed the calculator too much. I'm sure people have met the limits of the z80 though.

Length 5:

Lbl F

Defines label F. Labels are jumped to by goto and sub(. When the label is not a number, F() works like sub(F).

Length 6

Return

"Returns from a subroutine. If not in a subroutine, the program will end." If a subroutine calls another subroutine on its tail, it does not need a return (though you may still want it for readability).

Length 7

Returnʳ

"Emergency exits the program from within any number of nested calls." The r is used to modify a lot of functions.

Answered by Old Badman Grey on November 19, 2021

Julia

Factoid: The Julia language was created as a fresh approach to technical and high-performance computing. It's free and open source.

Note: Though not a requirement of the competition, every snippet here can be evaluated at the Julia REPL without issue.


Length 7:

@time 1

Julia has built-in tools for profiling code. Among them are @time and @allocated, which are actually macros. Here we're using the former.

From the documentation:

A macro to execute an expression, printing the time it took to execute and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

From the source code (at the time of writing):

macro time(ex)
    quote
        local b0 = gc_bytes()
        local t0 = time_ns()
        local g0 = gc_time_ns()
        local n0 = gc_num_pause()
        local nfs0 = gc_num_full_sweep()
        local val = $(esc(ex))
        local nfs1 = gc_num_full_sweep()
        local n1 = gc_num_pause()
        local g1 = gc_time_ns()
        local t1 = time_ns()
        local b1 = gc_bytes()
        time_print(t1-t0, b1-b0, g1-g0, n1-n0, nfs1-nfs0)
        val
    end
end

So what happens when we time the integer 1 at a freshly opened REPL?

julia> @time 1
elapsed time: 0.000521626 seconds (13880 bytes allocated)
1

13880 bytes allocated to print the number 1?! That seems a little excessive. But as it turns out, most of the allocation is due to the fact that Julia is JIT compiled. (Thanks to Martin Büttner for correcting me on the reason!) But if we were to run this again in the same session, we'd get something a little different:

julia> @time 1
elapsed time: 3.04e-6 seconds (80 bytes allocated)
1

That's much better!


Length 6:

≠(1,0)

What is that blasphemous character?! Those of us used to programming in the realm of ASCII may be initially put off by the presence of non-ASCII characters in source code. But fear not! Julia has your back. You can use a finite set of Unicode characters for input.

The operator is equivalent to !=, i.e. "not equal to". You can write it like ≠(1, 0) as in the snippet, or like 1 ≠ 0. Since 1 is obviously not 0, this returns true.


Length 5:

read!

No, Julia isn't commanding you to get up from your computer and read a book. In fact, read! is a function. In Julia, functions which modify their arguments end in !. In this case, read!(s, a) reads binary data from an input stream s and writes it to an array a.


Length 4:

1//0

Have you ever thought to yourself, "Man, I wish I could store an exact ratio of integers rather than a decimal value"? If so, you're in luck: Julia has a rational number type!

"But wait," you say, "I thought only Chuck Norris could divide by 0." Actually, Julia can deal with infinite rationals such as this one. However, it can't do 0//0... Only Chuck Norris can do that.


Length 3:

34

Julia has a built-in function akin to Matlab's backslash () operator that performs matrix division using a polyalgorithm. So Ab solves the matrix equation Ax=b for x. When you give it integers, like in this example, it's solving the trivial equation 3x=4, so the result is 4/3 = 1.333333.


Length 2:

im

This is a global constant which represents the "imaginary" number i, which is the principal square root of -1. Julia has a predefined type for complex numbers which supports all standard mathematical operations!


Length 1:

:

This returns colon(). The colon is used to construct ranges, like start:stop (assuming a step size of 1) or start:step:stop. Indeed, : actually calls the colon() function, so 1:4 is equivalent to colon(1, 4).

Answered by Alex A. on November 19, 2021

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

Answered by robbie on November 19, 2021

Swift

Factoid

Swift is a compiled language created by Apple, introduced in 2014 and is meant to replace Objective-C, the first supported language for OSX and iOS. Swift is currently used for iOS, macOS, tvOS and watchOS development. It uses the LLVM Compiler

It focuses on writing less code (compared to Objective-C, which is very verbose) and handling safer types. It features type inference, first-class type functions, closures, optional types, enum associated values and many more.

Swift is REPL, you can make your own idea by trying it on http://swiftstub.com/, or http://www.runswiftlang.com (these sites were shut down), use https://swift.sandbox.bluemix.net/#/repl instead.
Sites keep being closed, use https://www.weheartswift.com/swift-sandbox/.

Snippets:

14

case let(8,x):

In a switch case, this statement is absolutely correct.
That switch must have a tuple with two values. When evaluating the expression, if the first value is 8, it enters the case and fills the x variable with the second value of the tuple so you can access it directly inside the case.

11

/** #YES */

In Swift 2.0, comments can be written in Markdown. This produces a big title with YES as text. It can be displayed with format in the help navigator or quick help in Xcode.

10

var i=10e8

It creates a double value with 1000000000.0 in it. You can even write it like this 1_000_000_000.0. Swift accepts different number notations for scientific or currency purposes. It all leads to the same value in memory, but helps to clarify source code.

9

f(#i:int)

When declaring a function, you have to name the formal and the actual parameter, but sometimes the actual parameter name is already a good formal parameter name. Instead of writing the name twice at declaration func myFunc(aMarvelousInt aMarvelousInt: int) you put a hash symbol in front of the parameter func myFunc(#aMarvelousInt: int).
This feature has been removed from Swift 2.0 because it's the default behavior. To prevent using the variable name as a method label, insert an underscore and a space before the variable name func myFunc(_ aMarvelousInt: int)

8

Array<T>

Swift have generics, you can only insert objects of the specified type. The short notation of that array is [T]. In case you want to insert different types in an array, you must specify the type AnyObject, or Any if you don't insert NSObjects inside.

7

let π=3

This declares a constant π containing a approximation of pi. In Swift, source code is in Unicode. Your variable names can even contain emojis ???.

6

"(i)"

This returns a String with the value of i in it. The backslash escape character followed by a value in parentheses evaluates the content and inserts it in the string, or if it's a printable object, it uses its description.

5

(3,7)

This is a tuple with two integers. Tuples can be used to make functions return several values. To get the values, you specify the index. (3,7).1 returns 7. You can also name the values at declaration and access them with an identifier. (hours: 12, minutes: 46, meridiem: "PM").minutes returns 46.

4

func

That's the way to declare functions. A function is a first class object.

3

let

That's the way you declare constants. Constants have an optimisation in the compilation phase compared to the var declarations. An example is let hoursInADay = 24.0. Type inference makes that constant a Double.

2

..

This was the operator for half opened range in Swift 1.0, but to avoid ambiguity with the closed range operator ..., it has been replaced with ..< in Swift 1.1

You can use them in for loops (for x in 0..<5), on in switch cases (case (0..<5): break)

1

;

All Semicolons are facultative, until you put more than one instruction in a line.

Answered by Crazyrems on November 19, 2021

Python

(mbomb007's post already has a plethora of Python snippets, but I thought I'd chip in with some quirkier facts)

Factoid

Python is a dynamically typed language with an emphasis on readability.

Length 1 snippet

1

In Python 3, the above is equivalent to True in the sense that 1 == True (and also 0 == False). Note that this doesn't necessary hold true in Python 2, where you can redefine the value of True.

Length 2 snippet

<>

<> is an obsolete comparison operator equivalent to !=. It still works in Python 2 (although its use is discouraged), and was removed altogether from Python 3.

Length 3 snippet

...

Python has a number of features which no builtin uses, but is there solely for the sake of third-party libraries. This Ellipsis object is one of them, and it is typically used for slicing. For example, if we have the following 3D numpy array:

array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

then a[..., 0] (equivalent to a[:,:,0]) gives all the first elements:

array([[1, 4], [7, 10]])

In Python 3 the ... literal can be used outside of the slicing syntax, which amusingly allows you to use it as a "to-do" marker in place of pass or NotImplemented:

def f(x):
    ... # TODO

Length 4 snippet

(1,)

A one-element tuple in Python.

Python has lists (e.g. [1, 2, 3, 4]) which are mutable, and tuples (e.g. (1, 2, 3, 4)) which are immutable. One common use for tuples is as dictionary keys, since lists aren't hashable.

A common beginner mistake is to leave out the comma above, i.e. (1), which is just the number 1 surrounded by parentheses. The one-element tuple is the only time you need a comma before the closing parens — it raises a SyntaxError if you try to put one in the empty tuple (), and is optional for tuples of length at least 2.

Length 5 snippet

0or x

There's a few things going on in this snippet, so let's take a look!

or is like || in many languages. In Python, A or B short-circuits, returning A (without evaluating B) if A is truthy, otherwise it returns B. For example, 1 or x always returns 1, as 1 is always truthy, and even works if x is not defined. On the other hand, 0 or x either returns x if x is defined, or throws a NameError if it isn't.

When golfing, we can usually drop the whitespace between a number and an or, such as 1 or x becoming 1or x. This is possible because 1or starts with a digit, making it an illegal Python identifier.

However there is one exception — 0or, which mysteriously throws a SyntaxError. Why? Because octal literals in Python start with 0o (e.g. 0o20 == 16), and the parser chokes when it reaches the r!

Note: In Python 2, octal literals may also start with a leading zero, e.g. 020.

Length 6 snippet

*x,y=L

This snippet demonstrates a special type of assignment in Python, where L is a list, tuple or any other sort of iterable.

In Python, you can "unpack" tuples and lists like so:

a,b = [1,2]

This assigns 1 to a and 2 to b. This syntax is also used for multiple assignment, such as

a,b = b,a+b

which is useful when writing a program that computes the Fibonacci series.

If the lengths on both sides don't match, then a ValueError is thrown. However, Python 3 introduced a new syntax, extended iterable unpacking (or more colloquially, "starred assignment") which allows you to do things like this:

*x,y = [1, 2, 3, 4, 5]

This assigns y to the last element, 5, and x to the rest of the list, i.e. [1, 2, 3, 4]. You can even do something like this:

a,b,*c,d,e = [1, 2, 3, 4, 5, 6, 7]

which assigns 1 to a, 2 to b, [3, 4, 5] to c, 6 to d and 7 to e.

Length 7 snippet

zip(*x)

zip is a function which takes a bunch of lists and, well, zips them up:

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]

Note: In Python 3 a zip object is returned instead, so if you want a list like above you'll need to wrap the call in list()

It's quite a convenient function if you have two or more related lists, and you want to link up their respective entries.

Now say you want to unzip the list — how would you do so? We can try to use zip again, but unfortunately this gives:

>>> zip([(1, 4), (2, 5), (3, 6)])
[((1, 4),), ((2, 5),), ((3, 6),)]

The problem is that everything is in the one list, but zip takes the individual lists as separate function arguments. To fix this we introduce the * splat operator, which takes a list/tuple/etc. and unpacks them as function arguments:

f(*[1,2]) ==> f(1, 2)

And the result is:

>>> zip(*[(1, 4), (2, 5), (3, 6)])
[(1, 2, 3), (4, 5, 6)]

Length 8 snippet

x='a''b'

The first time I saw this, I was a little taken back — what does it mean to have two strings next to each other? The answer was simple:

>>> x
'ab'

Python merely concatenates the two strings! This is extremely useful for readability, since it allows you to break up long strings like so (note the surrounding parentheses):

x = ('This is a very long sentence, which would not look very nice '
     'if you tried to fit it all on a single line.')

Length 9 snippet

0!=2 is 2

You may already know that Python allows chaining of comparison operators, so 5 < x <= 7 is only true if 5 < x and x <= 7. If you didn't know that... then surprise!

Anyhow, lesser known is the fact that, since is/is not/in/not in are also comparison operators, they can be chained too. In other words, the above code is equivalent to (0 != 2) and (2 is 2), which is True.

Note: There are a few subtleties with the 2 is 2 half though, since is checks whether two things are the same object, not whether two things are the same value. Python caches small integers so 1+1 is 2 is True, but 999+1 is 1000 is False!

Length 10 snippet

x=[];x+=x,

What happens when you add a list to itself? If we try printing x, we get:

[[...]]

Fortunately, Python's print is intelligent enough to not explode trying to print recursive lists. We can then do a bunch of fun things, like:

>>> x[0][0][0][0][0]
[[...]]
>>> x[0] == x
True

This feature also works with dictionaries, and is one way of creating data structures with cycles, e.g. a graph.

Length 11 snippet

help(slice)

The help function is very useful for debugging in Python. When called with no arguments in REPL, help() starts a help session, in which you can look up documentation for functions/data types/etc. When called with a specific argument, help will give information on the related item.

For example, help(slice) gives the following information (truncated since it's quite long):

Help on class slice in module __builtin__:

class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 | ...

As for slice, as we can see we can create slice objects for indexing. For example:

>>> L = list(range(10))
>>> L[slice(2, 5)]         # L[2:5]
[2, 3, 4]
>>> L[slice(2, None)]      # L[2:]
[2, 3, 4, 5, 6, 7, 8, 9]

Another useful function for debugging is dir(), which returns all names in the current scope when called without an argument, and returns all attributes of a given object when called with an argument.

Length 12 snippet

round(5.0/2)

What does this evaluate to? The answer depends on your Python version!

In Python 2, division between two integers results in integer division (i.e. 5/2 == 2) whereas in Python 3 we get float division (i.e. 5/2 == 2.5). However, this is division between a float and an integer, which should always result in a float. Why would we get different results then?

If we take a look at the documentation for round for both Python versions, we'll find the answer:

  • In Python 2, round tiebreaks by rounding away from 0.
  • In Python 3, round tiebreaks by rounding towards the closest even integer.

In other words, 5.0/2 = 2.5 rounds to 3 in Python 2, but rounds to 2 in Python 3. Rounding towards the closest even integer might sound weird, but it's actually called banker's rounding, and tries to treat positive and negative values similarly to reduce bias.

Length 13 snippet

class C:__x=1

Being object-oriented, Python has classes. The above is a class C which has a single attribute __x set to 1.

We can access class attributes using dot notation. For example, if we have the class

class MyClass(): my_attr = 42

then printing MyClass.my_attr would result in 42, as expected.

However, if we do the same and try to access C.__x as defined above, we get:

AttributeError: type object 'C' has no attribute '__x'

What's going on? C clearly has an __x attribute!

The reason is that attributes starting with __ emulate "private" variables, something which Python does not have. Python mangles the name of any attribute starting with __, appending the class name so that name reuse conflicts are avoided. In the above example, if we were really determined to access that 1, we would instead have to do

>>> C._C__x
1

Length 14 snippet

NotImplemented

Not only does Python have classes, it also has operator overloading. For example, you can have a class

class Tiny():
    def __lt__(self, other):
        return True

where __lt__ is the less-than operator. Now if we make an instance of Tiny, we can do this

>>> t = Tiny()
>>> t < 1
True
>>> t < "abc"
True

since we've defined __lt__ to always return True. Note that we can also do

>>> 42 > t
True

but the following breaks:

>>> t > 42
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    t > 42
TypeError: unorderable types: Tiny() > int()

Wait, how does that work? We haven't specified a behaviour for greater-than with Tiny, so it's not surprising that the last case breaks. But then how does an int (42) know that it's greater than our Tiny object?

Python has a builtin constant NotImplemented, which can be returned by a comparison special method. Let's try it out:

class Unknown():
    def __gt__(self, other):
        # __gt__ for greater-than
        print("Called me first!")
        return NotImplemented

Now if we make an instance of our new class:

>>> u = Unknown()

We can do this:

>>> t < u
True
>>> u > t
Called me first!
True

As we can see, what happened for u > t is that Python tried to call the greater-than method for Unknown first, found that it was not implemented, and tried the less-than method for the other class (Tiny) instead!

Length 15 snippet

x=[],;x[0]+=[1]

This is a bit of a fun one. First we assign x to be [], which is an empty list inside a tuple, i.e. ([],). Then we do x[0]+=[1] which tries to extend the empty list inside by the second list [1].

Now, remember that lists are mutable and tuples are immutable – what happens when you try to change a mutable object inside an immutable object?

>>> x=[],;x[0]+=[1]
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    x=[],;x[0]+=[1]
TypeError: 'tuple' object does not support item assignment

Oh so it gives an error, I guess that's to be expected. But what if we try to print x?

>>> x
([1],)

Huh? The list changed!

If you're curious about what's happening here, be sure to check out this blog post.

Length 16 snippet

@lru_cache(None)

Just add cache! This is a simple example of a decorator available in Python 3.

Suppose we have the following naïve Fibonacci implementation:

def f(n):
    if n < 2: return 1
    return f(n-1) + f(n-2)

As most introduction to programming courses may tell you, this is a very bad way of implementing Fibonacci, leading to exponential runtime since we're effectively just adding a lot of 1s at the base case. f(10)? Runs in a split second. f(32)? Take a while, but it gets there. f(100)? Nope.

But if we cache the results, things should get a lot faster. We could always use a dictionary for the cache, but let's try something else instead:

from functools import lru_cache

@lru_cache(None)
def f(n):
    if n < 2: return 1
    return f(n-1) + f(n-2)

As we can see, all I've done is import lru_cache from the functools module and added @lru_cache(None) before my function. @ denotes a decorator which wraps around a function, in this case for memoisation. lru_cache's first argument is maxsize, the maximum size of the cache – here we've set it to None to indicate no maximum size.

Now if we try to use it:

>>> f(100)
573147844013817084101

And it didn't even take a second!

Note: f(1000) leads to a recursion depth error, but that's a story for another time

Answered by Sp3000 on November 19, 2021

APL

Factoid

APL (A Programming Language) started out as an interpreter for a formula notation devised by Ken Iverson. When the language was designed, people used teletypwriters to communicate with computers. The character set of these was limited, but due to their construction, one could put multiple characters into the same position to compose complex characters. This feature is heavily used by APL, contributing to its infamous reputation as a read-only language.

You can try out most of the examples on http://www.tryapl.org.

Length 1

The character , called lampshade, both for its shape and for the enlightment you get from its presence, introduces a comment. Historically, it was created by overstriking a (jot) and a (up shoe).

Length 2

⍳3

The monadic (one argument) function (iota) generates a vector of the first few natural numbers. For instance, the aforementioned ⍳3 would yield 1 2 3, the vector of the first three natural numbers. On some implementations of APL, it would yield 0 1 2 instead, this depends on the value of ⎕IO, the iota origin.

Length 3

53

As opposed to the monadic , the dyadic (expand) function copies the argument on the right as often as the argument on the left; thus, 53 yields 3 3 3 3 3. You might want to play around with vector arguments (like 1 2 34 5 6) to see what it does then.

Length 4

A←⍳3

This assigns to A the value of ⍳3. (left arrow) is the assignment operator. An assignment doesn't have to be the leftmost thing in a statement; assignments are parsed like function calls and yield the assigned value for further use.

Length 5

∘.×⍨A

A three by three multiplication table, that is,

1 2 3
2 4 6
3 6 9

This is a little bit complicated, so let me explain. ⍺∘.f⍵ (read: alpha jot dot f omega) is the outer product of and over f. The outer product is a table of the result of applying f to each possible pair of elements from and . In this example, f is × (multiply), yielding a multiplication table. The operator (tilde diæresis) commutes its arguments, that is, ⍺f⍨⍵ is equal to ⍺f⍵ and f⍨⍵ without a left operand is equal to ⍵f⍵. Without the commute operator this snippet would be a∘.×a. The outer product operator is very versatile; check out what happens if you substitute = for ×!

Length 6

{×/⍳⍵}

A factorial function. A pair of curly braces encloses a dfn (dynamic function), that is, an anonymous function (cf. lambda expressions). The arguments to a dfn are bound to the variables and or just if the dfn is called as a monadic (single argument, as opposed to dyadic, two argument) function. We apply to the right argument, yielding integers from 1 to . The / (slash) operator reduces, that is f/⍵ inserts f between the items of . For instance, +/⍳5 is just 1+2+3+4+5. In this case, we reduce with ×, yielding the product of the items of ⍳⍵, which is just the factorial of .

Length 7

2×3*4+5

Yields 39366. ⍺*⍵ (alpha star omega) is raised to the power of . APL has a very simple precedence rule: Everything is evaluated from right to left, all functions are right-associative. Operators bind stronger than functions and are evaluates from left to right. Thus, the expression above with explicit parentheses would be written as 2×(3*(4+5)) as opposed to the usual (2×(3*4))+5.

Length 8

¯1+3 3⍴A

This snippet yields

0 1 2
3 4 5
6 7 8

and demonstrates two important concepts: The first concept is the (rho) function, which reshapes its right argument to the shape specified in its left argument. The shape of an array is a vector of the lengths of each axis in the array. The shape of a scalar is the empty vector. Thus, 3 3⍴A reshapes A into a three by three matrix. The second concept is how addition is used here: We add ¯1 (overbar one), meaning negative one (¯ is a prefix to specify negative numbers, while - is an operator) to an array. The two operands have different shapes, so the operand with the lesser shape is distributed onto the other operand, subtracting one from every item in the generated matrix.

Length 9

+.×⍨3 3⍴A

A, reshaped to a 3 by 3 matrix, multiplied with itself. The . (dot) operator takes two functions and constructs an inner product, where the first function represents addition and the second function multiplication. A plain, old, matrix multiplication is +.×, a common variant is ≠.∧ (where is not equal and (up caret) is logical and) for boolean matrices; many interesting things can be modelled as an inner product with certain operators in place of + and ×.

Length 10

(.5×⊢+÷)⍣≡

(read: left parenthesis dot five multiply right-tack plus divide right parenthesis star-diæresis same) Compute the square root of a real using the Babylonian method. The left argument is the number you want to compute the square root of, the right argument is the initial guess for the square root. I originally wanted to provide a meaningful initial guess, but I ran out of characters (append to use the number itself as the initial guess).

So how does this work? Let's start with the left part, (.5×⊢+÷), first. This expression uses tacit notation originating in J which was later ported back to Dyalog APL. Tacit notation is a bit hard for beginners, so please read this section carefully. An isolated sequence, such as +/÷≢, which the “normal” parsing rules do not resolve to a single part of speech is called a train. A train of two or three functions produces a function and (by repeated resolution), a function train of any length also produces a function. A train of three functions fgh behaves like {(⍺f⍵)g⍺h⍵}, that is, f and h are applied to the arguments of the resulting function and the result of these are applied to g. A train of an array and two functions like Afg behaves like {Af⍺g⍵}, this is, g is applied to the arguments of the resulting function and A and that result are applied to f. A train of two functions has a semantic, too, which is explained in the documentation but not used in this example.

In this particular train, one new function, (right tack) is used. It behaves like {⍵}, yielding its right argument. Thus, the entire expression is equal to {.5×⍵+⍺÷⍵}, which is just the iteration step of the Babylonian formula. It is easy to see how tacit notation benefits the golfer; it allows you to shave of quite a few precious characters where applicable.

The last piece of the puzzle is the (star diæresis), power operator. If the right argument is an array, f⍣A⍵ applies f to a total of A times. For instance, f⍣3⍵ is equal to fff⍵. The count can be negative, in which case APL tries to infer an inverse function of f and applies that. If the right argument to is a function, too, f⍣g⍵ applies f to until (fY)gY where Y is the result of the repeated application of f to . Notably, if g is = (equal) or (same), f⍣≡ computes a fix point of f. This is exactly what we need for the Babylonian method! We want to iterate until the result converges. Lastly, if applied to a pair of things is invoked as a dyadic function, the left argument is bound to f on the left, i.e. ⍺f⍣g⍵ is equal to (⍺∘f)⍣g⍵ where A∘f behaves like {Af⍵}.

Answered by FUZxxl on November 19, 2021

Lua

Factoid

Lua is a dynamic, lightweight yet powerful, highly portable (pure Ansi C), fast and easy to learn scripting language.
Initially designed to be a configuration language and to be embedded in applications to script them, it is also used as a glue between native libraries and to be a standalone language on its own.

Length 1

;

You will nearly never see a semi-colon at the end of a Lua statement (unless that's the taste of the coder!), as they are totally optional and, most of the time, unnecessary. They can be used if you want to put two statements on the same line (even then it is optional: a = 5 b = 3 is OK (but ugly!)) and to avoid some ambiguity: a = f (f1 or f2)(x) can be seen as a = f; (f1 or f2)(x) or as a = f(f1 or f2)(x) (call of f with a function argument returns a function which is called with x as argument).
The semi-colon can be used as separator in table literals, too.

Length 2

..

That's the string concatenation operator in Lua. If we concatenate a number, it is converted to string. For something else than strings or numbers, the __concat metamethod is called (more on this later).

Length 3

nil

is a special value, whose main property is to be different from any other value... It is generally used to represent the absence of a useful value, equivalent to null in some other languages.
It is the only other value that is "falsy" (the first one being false, of course), any other value is coerced to true in a conditional expression.

Length 4

f's'

The function f is called with the literal string "s". Note that literal strings can use single quotes or double quotes as delimiters.
Here, as a function called with a single, string argument, we can omit the parentheses. That's syntax sugar for f('s'). This can be used for writing some nice DSL.
This syntax shortcut can be used too when the single argument of the function is a table.

Length 5

a={1}

The variable a is assigned with a table with one entry, 1.
Here, the table is treated as an array. We will see they can be also associative arrays (key / value).
Table is a fundamental data structure in Lua, so it is optimized and efficient: it can have both an array part (with fast numerical index access) and a hash part for the associative side.

Length 6

[[n]]

A literal string (long format) made of two characters: backslash and n. The [[ ]] notation allows to write multi-line strings with no escapes inside. Newlines are kept literally (except the one immediately after the opening bracket, if any: it is ignored for convenience of formatting).
Lua allows nesting of long literal strings (eg. if you want to put one inside another) by putting a number of = sign between the two brackets. Of course, matching closing brackets must have the same number of equal signs.

Length 7

t={k=v}

A table defined as associative array: here, k is a shortcut for ['k'], a string key (the latter annotation is useful for string keys that are not valid identifiers). v is a variable, its value will be the value of the entry.
The key (index) can be any Lua value, except nil. The value can be any Lua value, but nil actually removes the entry.
Access to entries can be done as t.k or as t['k']. The first form is valid only if the key is a valid identifier, otherwise we have to use the second form.

Length 8

a,b=f(x)

A function can return several values (put them after the return keyword, separated by commas), and these values can be assigned at once to several variables.
If the function provides more values than the number of left-hand variables, the extra values are dropped.
If it doesn't provide enough values, the extra variables get nil as value.
A common pattern in Lua is to return either a single value, or nil and an error message if something went wrong.

Length 9

--[[ C ]]

A block comment. Line comments are marked with a double dash. Block comments extends this notation with a block of text (potentially multiline) marked between double brackets. Actually, they use a syntax similar to long literal strings, including the equal signs between the brackets, whose number allows to distinguish nested blocks. This allows to avoid conflicts with other block comments or long literal strings when commenting out a long block of code.

Length 10

local v={}

Lua started its career as a configuration language, and is still useful as such. Because of this, its variables are global by default, ie. they are attached to the built-in _ENV variable and visible everywhere. That's also where we find the standard libraries, for example.
Of course, this global environment is to be avoided for most usages, because of collision risks, encapsulation issues, and because a global variable is slower than a local one.
Lua supports lexical scoping, we can define variables that are visible only within their scope, their chunk (from the declaration point to the end of the chunk) and the nested chunks.
The statement above declares a local variable initialized to an empty table.
For performance reason, a common practice is to bring global functions to the local scope, like local print, find = print, string.find.

Length 11

a,b,c=b,c,a

As seen, a function can return several values, which can be assigned in one go to several variables.
It also works with several values (separated by commas) on the right hand side.
The expression above cyclically permutes the values of a, b and c, ie. a takes the value of b which takes the value of c which is assigned the value of a. It is a variant of the a, b = b, a expression which swaps two values.

Length 12

::L:: goto L

The programming world frown upon the usage of GoTo, but the Lua authors consider it is malevolent only in bad hands... They introduced it in Lua 5.2 to answer a frequently asked feature: adding a continue statement. The goto statement effectively allows to jump to the end of a loop, and also allows to break out of several nested loops. Note that Java, which has goto in its reserved words, doesn't implement it, but have named break allowing such feature...
Here, goto SomeName jumps to a scoped label named... SomeName, which is defined by surrounding the name with double colons like ::SomeName::

Length 13

(a or b){x=1}

This is a function call with a table as argument. Lua allows the syntax sugar of omitting the parentheses around the argument if it is unique and it is a table, similar to the call with a string seen at length 4. It allows to create some nice DSLs...
Here, we also see a logical expression between two functions: if a is defined, it is called with the argument. If it is not defined, ie. has the value nil, then that's b which is called (assuming it cannot be nil). This fallback syntax is idiomatic in Lua to provide default values to variables. It has the same function than the ternary operator of C-like languages (a ? a : b)
Note that in Lua, logical operators are spelled out: or and not instead of C's || && !, slightly less readable for newbies.

Length 14

_ENV={p=print}

Starting from Lua 5.2, local environment of a current function is exposed using variable _ENV. While its default value is _G, global environment, as any other variable, it can be assigned any value!
Here, we change local environment, one from which free names are resolved, to table including single key-value pair with string key p and value being built-in function print. After this assignment, p will be the only resolvable name in current environment.

Length 15

ffi.load'mylib'

While Lua have official implementation in ANSI C, others exist as well. One of most well-known ones is LuaJIT, in which this line would load C library called mylib.so on UNIX or mylib.dll on Windows and expose its functions directly to your Lua code. In addition to this, LuaJIT implements JIT-compilation for Lua code, greatly increasing its speed compared to official interpreter.
However, LuaJIT's last release was back in 2017 and it also implements Lua 5.1 API, making its usage now somewhat questionable. Newer JIT compiler for Lua is Ravi, that's based on LLVM and targets Lua 5.3 API. It also implements some language extensions.

Length 16

function N(a)end

You can create global functions with the function keyword followed by a name.

Length 17

N=function(a) end

The above snippet is syntactic sugar for this. local function N()end is sugar for local N=function()end. This is allowed because functions are first-class values.

Length 18

("n=%d"):format(3)

Wow, lots to introduce. This formats the string n=%d, replacing the %d with the number 3. The : denotes a method call, which is the same as calling ("n=%d").format("n=%d", 3). But wait, "n=%d" doesn't have the property format! Instead, since it isn't a table and doesn't have this property, Lua looks at its metatable, the global string table, and finds the format property there. Metatables are kind of like prototypes in Javascript. It then calls the string.format function with "n=%d" and 3 as its arguments, and returns "n=3".

Answered by PhiLho on November 19, 2021

LambdaMOO

LambdaMOO is a server for running an object-oriented MUD which can be programmed live by the players themselves. The LambdaMOO server handles the telnet connection for each player, reading in what the player types, parsing it and running the correct verb. It also persists all of the objects to a database, meaning you can shut down a server and bring it back up and the environment will be exactly where you left it. (It's much like a smalltalk image in this regard.)

The oldest running LambdaMOO server (up since 1991) is at lambda.moo.mud.org; you can telnet to port 8888 and log in as a guest to look around.

This answer will cover the LambdaMOO programming language (which has no separate name), but will of necessity touch upon other aspects of the LambdaMOO environment, such as the server, players and databases.

Some interesting links if you'd like to learn more:

Factoid

LambdaMOO code is stored as bytecode and decompiled for editing. The original intent was for it to be stored and edited offline, then uploaded to the server. In practice, it turned out to be easier to edit it live on the server, so a decompiler was implemented. The bytecode is expressive enough that this tends not to be an issue, and it has the advantage of enforcing a uniform coding style!

Length 1

;

Like many languages, LambdaMOO statements are semicolon-terminated, and an empty statement is valid. However, it is optimised away by the compiler and won't be there when the program is edited again! (This same compiler optimization also cleans up empty else statements and the like.)

; is also used as a synonym for eval at the beginning a line of user input, allowing programmers to test code without writing an entire verb. (Normally, user input is interpreted as English-like commands such as go west or take the box.)

Length 2

Because it is designed for programming an interactive environment, LambdaMOO objects are persistent and are identified by a unique number. They have two types of data associated with them, properties (data) and verbs (code). Both properties and data are inherited from an object's parents, and can be overridden.

Object numbers are represented as #nnn.., starting from 0 and counting up. The first LambdaMOO server (lambda.moo.mud.org) has been running since at least early 1991 and is up to #124703. It would be a lot further than that if they hadn't implemented object number reuse around 1996. Objects are not usually created and recycled automatically; instead, they are created by players to represent persistent "physical" objects--rooms, players, a wind-up duck, and so on. Because of the "Virtual Reality" design, even objects which wouldn't ordinarily be physical are generally represented as such on a MOO. For instance, the database of player's birthdays is "a computerized datebook shaped like a big birthday cake."

There are two objects of particular interest to be found in every MOO database:

  • #0 is The System Object. It is the only positive object (negative ones will be covered under Length 3) which is treated specially by the server.
    • Various verbs of #0 are called by the server when events happen, such as a player typing a line, the server starting or stopping, and so on. It is the job of these verbs to handle the event as necessary; thus, the database (and the verbs of #0 defined therein) define most of the behavior of the actual server.
    • Properties of #0 are used for a special syntax for referring to objects globally, without memorizing their object number. If #0 has a property named "foo" set to #1234, $foo can be used anywhere to refer to #1234.
  • #1 is the Root Class, the parent of all other objects. LambdaMOO (like JavaScript) uses prototypal inheritance rather than the more common class-based inheritance. Every object has a parent, from which it inherits any properties and verbs that are not defined on itself. (#1 is the parent of both itself and #0.) #1 defines a few verbs and properties which should exist on every object, such as a name and description, as well as various verbs to handle events such as: creation and recycling; moving things into and out of the object; moving the object into and out of other objects; and handling user input and output.

Length 3

LambdaMOO uses negative object numbers to represent special things which do not actually exist, but which must have an object type so they can be manipulated in the same way as a normal object.

  • #-1 - $nothing - An object which is not. Most commonly seen in the context of object locations: all objects must have a location; objects which don't need to be inside of something else have their location set to #-1.
  • #-2 - $ambiguous_match - Used as a placeholder when the user's input could have matched multiple objects. For instance, "ball" in a room with a "red ball" and a "blue ball" will be represented as #-2 (generally causing a "which did you mean?" error message).
  • #-3 - $failed_match - Used as a placeholder when the user's input couldn't be matched to any object. For instance, "ball" in a room which only contains a "red cube" and a "blue cube". This generally causes an "I see no x here."-type message.
  • #-4 and below are used to represent players who have not logged in yet (that is, they're still at the login screen). These players need an object number so the code can interact with them, but can't be given a positive one because the server doesn't know who they are yet. When I log in, for instance, my connection might be given #-6 until I log in, at which point the connection is re-associated with my actual player object, #124434.

Length 4

verb, dobj, iobj: When the user types in a command, it is split up according to the form verb [direct-object [preposition indirect-object]]. (For example, look, take ball, give ball to Henry.)

direct-object and indirect-object are matched to an actual object (or #-1 or #-2 if necessary) and verb is called on whichever object is found to have a matching one first. (It searches the player, the room, the direct object, and the indirect object, in that order.) That verb can then use the special variable verb to find out what it was called as (equivalent to $0 in a bash script), and dobj and iobj to determine the objects that were matched to the direct and indirect objects. There are also special variables for the preposition, as well as the actual strings (rather than matched objects) for the direct and indirect objects.

Length 5

1?2|3 - This is the syntax for the ternary conditional operator; in most c-type languages it would be 1?2:3 instead. There is no special type for binary values; rather, each possible value for each possible type is categorised as either true or false. True values are ints and floats other than 0 and non-empty strings and lists. Everything else is considered false, including 0, "", {}, and all objects. Thus, 1?2|3 evaluates to 2.

Length 6

player is another special variable (like dobj et al), but it refers to the player object that executed the command. For instance, when I (#124434) type pull lever on contraption, the contraption:pull verb has the player variable set to #124434. This is most commonly used for output: the player has a tell verb which sends a line of text over the correct network connection to the person's computer, so they can read about the antics of the horde of lemmings they have just unleashed on an unsuspecting Barney. (The Rube Goldberg Contraption has to be seen to be believed. Telnet to lambda.moo.mud.org port 8888 and go southeast from the Living Room.)

Length 7

"ab"[2]

Strings are represented with the usual double quotes, and list indexes are done with square brackets. Unlike many languages, lists and strings start indexing with 1 rather than 0. Thus, this expression returns "b".

Length 8

#1:huh() is the shortest verb call I could come up with. Verbs are the same as a method in most other languages; the syntax for calling them is #nnn:verb([arguments...]).

You wouldn't generally call :huh() directly; it is called by the default core when a player tries to do something to an object that the object doesn't support. For instance, globnitz ball will look up ball (say it's #1234), discover that #1234:globnitz doesn't exist, and call #1234:huh() instead. The default implementation of #1:huh just tells the player I don't understand that.

Length 10

create(#1)

The create() function call is used to create a new object. The argument is the parent object; create() then returns a new object which is a child of that object. (Some forks of the LambdaMOO server, such as stunt, also support multiple inheritance. It works more or less as you would expect.) Thus, this command creates a new object which inherits the properties and verbs of #1, described above.

Unlike most object-oriented programming languages, objects in LambdaMoo are not something you create very frequently. This is partly for technical reasons: there is generally a quota which limits the number of objects a player can own, to reduce database bloat. However, it is mostly because objects are very much a physical thing (inasmuch as anything can be physical in a virtual world). If you make an object, players can see it, pick it up and carry it around.

There are patches which you can apply to the LambdaMOO server to get something that resembles a traditional object; these are called "waifs" in LambdaMoo parlance. Waifs have properties and verbs but don't have object numbers, are automatically garbage-collected when they leave scope, and do not appear in the world. If you want to use these you will need to compile the server with the waif patches applied.

If your server has object recycling enabled, the object reference you get is not guaranteed to be unique: it may have been used by a different object in the past. When creating an object this is not an issue, since you have never heard of whatever it was before. However, you need to bear this in mind when using object numbers: #1040 which used to be a vacuum cleaner may have been recycled into a tax form since you last used it. In practice, this is not usually a problem: just as you wouldn't throw out a perfectly good vacuum cleaner, you don't recycle a useful object. (I've found that you usually run into this problem only when you have a reference to something a different player owns, and that player is reaped: all of their objects get recycled.)

Answered by Wolfgang on November 19, 2021

Befunge-98

(No love for my favorite language?)

Befunge is a 2D programming language operating on a toroidal space - the 'grid'. In addition to the normal operators (all of which are single ASCII characters), there are also special instructions that change the direction in which the instruction pointer moves through the grid. The language was designed to be as hard as possible to compile, to this end, it contains elements of self-modification.

There are two versions of Befunge: Befunge-93, the first version (which limits the grid size to 80x25 and, as such, is not Turing-complete); and Befunge-98, the final specification (which allows unlimited grid size and much other useful functionality). In this post, I will use Befunge-98 for the code snippets because I feel it is the more useful of the two; a note will be included next to those snippets which are compatible with Befunge-93.

I recommend using CCBI to run longer code in Befunge-98. There are some other options for if you want to see Funge-space and the stack while the program is running: this online Befunge-93 interpreter (with 'klunky' input), and this online Befunge-98 interpreter (with no input at all, though it runs fast).

Snippets

Length 1 (Also works in Befunge-93)

.

Prints out 0, forever and ever and ever. Because Befunge's space is toroidal, the pointer wraps around when it encounters an edge. Befunge starts with an empty stack for its memory; trying to pop or do operations on an empty stack makes it 'generate' as many zeroes as needed for the operation.

Length 3 (Also works in Befunge-93)

&.@

(Still kind of a boring example, but less so.) This one accepts a decimal number (&) from stdin and prints it (.) to stdout. Then - aha, a new feature! - it terminates at the @. This is a pretty boring program, but you can only do so much with three characters...

Length 4 (Also works in Befunge-93)

1+:.

Another infinitely looping program. Each loop takes the top number on the stack and increments it, duplicates it (with :), and prints one of the duplicates, leaving the other on the stack for the next loop. (Since printing a number removes it from the stack, duplication is needed in order to keep a copy.) The result of this is a program that prints the positive integers, starting from 1.

Length 6 (Also works in Befunge-93)

8:*00p

Unless the user can watch Funge-space while the program is executing, this program appears to do nothing. In fact, it even terminates, rather than looping infinitely. "How?" you might ask. "You said before that the @ operator ends the program, and there is no such thing here!" Here lies one of the most intriguing aspects of Befunge: the ability for the program to modify its own instruction space.

The p operator takes a number, let's call it n, and a coordinate pair x, y (in order such that y is on top of the stack), and puts the character with codepoint n in the Funge-space grid square at the given coordinates. In this case, it puts an @ (ASCII value 64, or 8*8, or 8:*) at position 0, 0 - the top-left corner of the program, where the 8 is initially. Then, wrapping around, the pointer hits the @ it just set down and stops - the program has modified its own code. There is also a g operator that grabs the value of the character at the given coordinates; in this way, the program space can also be used as program memory that's more convenient than the stack.

Here's where Befunge starts to show its true colors! It's a cunning and devious language.

Length 7

~:a`j@,

Here we start seeing interesting constructions, and also some features that are not in Befunge-93. This program takes exactly one line of text and prints it out again - specifically, it keeps accepting characters from stdin (using ~) and checking whether the character is greater than 10 (a, new to -98), the value of a newline. If it is, it prints; if not, it terminates. This is accomplished using j (also new to -98), our first control operator - which pops a value and jumps over that many instructions - in this case either 1 (if the character value is greater than 10) or 0 (if it is not).

Length 8

1#;::.+;

This introduces the # operator, or trampoline, which jumps the instruction pointer over the next symbol to execute - the same as 1j. It originated in Befunge-93, due to the necessity of such an operator in a two-dimentional language. We can also see ;, a 98-exclusive operator that also moves the pointer around - this one jumps it all the way to the next ; along the direction the pointer is moving. Here it's used to create an infinite loop so the initial 1 only pushes a 1 at the beginning. The end result is a program that prints out, starting at 1, sequential powers of 2 forever and ever.

Answered by Kasran on November 19, 2021

Rebol 2

Note: There is already an answer for Rebol, but it is specific to Rebol 3, which has some significant differences. I wanted to highlight some of the features that are unique to Rebol 2 as these deserve a mention.

Factoid: Rebol stands for "Relative Expression Based Object Language". It is a homoiconic language (that is, code and data are expressed the same way).

1

?

This brings up the built-in help in the command-line interpreter. It is a mezzanine function.

2

[]

Evaluates to an empty block (type block!) which groups together values and functions and is a container for data until it is evaluated, in which case it is treated as code. Elements of blocks, even nested blocks, can be accessed via a path.

3

pwd

Evaluates to a value of type file! that is the current working directory, just like in the shell! Rebol provides some familiar shell commands, like cd, ls pwd and rm as mezzanine functions which behave like they would in the shell, so you can navigate around, and work with the file-system and forget that you are actually in the Rebol interpreter!

4

12x3

Pairs. They are everywhere, right? In spatial co-ordinates, screen dimensions, on the park bench. pair! is another built-in type that consists of two integers separated by an x, just like you write it and would like to read it. But there's more: You can slice them, dice them, add and subtract them, get at their values with /x and /y (/ being the refinement modifier that allows you to access things like values in objects or entries in arrays using a very natural, path-like syntax).

5

2 + 2

The + here is in fact an operator function, or infix function, taking two arguments: one on the left and one on the right. Typing ? op! at the Rebol console will give us a list of all these operators (type op!) which includes the usual suspects, like != and <> (both meaning not equal), ** (power-raiser) and xor (exclusive XOR) among others.

Answered by mydoghasworms on November 19, 2021

Smalltalk

Smalltalk has five keywords. The entire spec fits on a single sheet of paper.

Smalltalk is a small language ;-), with only a minimum number of builtin semantic features - basically the language only defines the syntax for how messages are sent to objects (that's what others would name "virtual function calling").

However, it comes with a big class library. This is open for inspection and extension, and includes everything from numeric operations to UI frameworks to compilers, editors, debuggers and class browsers.

Smalltalk is pure object oriented, with no exceptions. Everything down to integers, characters, stack frames, methods and closures is represented as an instance of a class. This includes classes themself, which are instances of a metaclass.

Every class can be extended, modified, subclassed or reinherited at execution time.

Every Smalltalk dialect comes with a powerful IDE, which makes heavy use of the above dynamic possibilities. For example, it is possible to change code in the debugger and proceed execution without any limitation. Programs are developed inside the IDE - that means that your application classes and objects live in the same world. There is no required separation between the IDE objects and the application objects, and each can make use of the other. of course, you can also extent the IDE itself, while you are living in it.

For programmers, the combination of powerful IDE and high dynamics due to the very late binding, make this a great environment for rapid development.

Length 1

Numbers evaluate to themselves - numbers are objects:

1

Length 2

Character literals (constants) are preceeded by dollar signs:

$1

Length 3

Strings are in single quotes, like in SQL:

'1'

Length 4

Literal arrays are stored in hash & parenthesis. These are created when a method is compiled, not at runtime, so it can improve performance:

#(1)

Length 5

Mixed mode arithmetic is done transparently. Values are coerced automatically as required:

1+2.0

Length 6

Blocks are anonymous functions. They can access the variables in their static scope. Blocks can outlive the dynamic scope in which they were created (i.e. they are Closures). Here is a simple block which returns its argument:

[:a|a]

Length 7

Smalltalk has builtin support for Fractional numbers. These compute exact values and thus avoid the usual floating-point rounding errors. Multiplying 1/3 by 9 gives an exact integer 3, not 2.9999999 as in some other languages:

(1/3)*9

Length 8

Scaled Decimal (FixedPoint) numbers are perfect for monetary values. They will print out with the specified number of fractional digits. Technically, they are fractions with a power-of-10 denominator. The following is a fixedpoint constant which always prints itself with 2 digits after the decimal point:

105.12s2

Length 9

In Smalltalk, assignment is done with ":=". The "Value comparison" operator is "=", as opposed to the "Identity comparison", which is "==". The following will assign a boolean true or false to b, depending on the numerical value of x (i.e. works for x being of ANY numeric type, such as Float, Int, FixedPoint etc.)

b:=(x=10)

Length 10

Intervals are collections, and as such can be used whereever other indexable collections can be used. For example, they can be enumerated with the "do:" messsage, passing a block like shown above; i.e. "(1 to:10) do:[:x |...]". The following creates an Interval representing the integer numbers from 1 to 10.

(1 to:10) 

Length 11

In Smalltalk, statements are separated by a period - just like in English. I added a space, to get 11 characters:

a:=0. b:=1.

Length 12

There's no real syntax for method definitions. You can create methods dynamically, but that takes a lot more chars to demonstrate. This is what you could see as a method definition in a class browser:

+ s
^self, s

This is a binary method called "+", that takes an argument "s". And it returns (^) the concatenation of the receiver with the argument.
Define it in class String to instantly uglify the language!

Length 13

This used to be 100 factorial, but that impresses nobody...

999 factorial

Open a browser, type it in and print it (alt p in Squeak/Pharo), don't be scared. I wonder if it's right though? Probably is...

Just to be sure:

999 factorial / 998 factorial

Answered by John Borden on November 19, 2021

Rust

Rust is a general purpose, multi-paradigm, compiled programming language developed by Mozilla Research. It is designed to be a "safe, concurrent, and fast."

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

These snippets are subject to change, since Rust syntax are not yet stable. Please give a comment when there are things that no longer work on latest Rust.

Length 75

fn a<T:Default>(v: T,p:&Display) -> T { println!("{:?}",p); T::default() }

For any Type that implements T (the default trait) and that calls function a in your code, the compiler will create a dedicated function that only that type will call and use. This is called monomorphization.

At the same time, all these new functions accept a value p, as a fat pointer (A pointer to the value, and the display implementation of that value).

These new functions can display the value p by dynamic dispatch (invoked by println!).

Length 9

fn main()

The main() function is the main function. Here's the example of hello world

fn main() { println!("hello world"); }

If saved as hello.rs, the source can be compiled and run using this command:

rustc hello.rs && ./hello

Length 8

fn x(){}

This is an example on how to create a function named x. The arguments can be written inside (), the statements or expressions can be written inside {}, and the return type can be written between ){ sign, for example:

fn x(a:i32, b:i32) -> i32 {
  if a == 0 { return b; }
  a + b // equal to return a+b;
}

The return keyword used to exit the function. Just like Ruby, the last expression in the end of the program will be returned when return statement not visited at runtime. Here's the exact same function without return keyword:

fn x(a:i32, b:i32) -> i32 {
  if a == 0 { b } else { a + b }
}

Length 7

if x {}

This is the if syntax of rust, this part similar to Go's if syntax. We could also write like this:

let y = if z == 3 { 9 } else if z > 3 { 12 } else { 15 };

Length 6

print!

The print! and println! is the standard output function. This function has similar syntax to .NET's String.Format method. Here's some example:

print!("{0} {1} {0}",123,234);     // 123 234 123
println!("{} {} {}",123,234,345);  // 123 234 345
print!("{a} {b} {c}",a=1,c=2,b=3); // 1 3 2

The {} symbol are called next argument specifier, {number} is positional parameter, and {string} is named parameter, we could mix any of them. To print the type of a value, you can use :? debug traits, see this link for another formatting traits.

println!("{:?}", 123 );
// 123i32

println!("{:?}", "abc" );
// "abc"

println!("{:?}", std::io::stdin().read_line() );
// some possible outcomes:
//  Ok("string that has been readn")
//  Err(IoError { kind: EndOfFile, desc: "end of file", detail: None })

println!("{:?}", std::io::stdin().read_line().ok() );
// some possible outcomes:
//  Some("string that has been readn")
//  None

println!("{:?}", std::io::stdin().read_line().ok().expect("Fatal: read_line failed!") );
// some possible outcomes:
//  "string that has been readn"
//  thread '<main>' panicked at 'Fatal: read_line failed!', /build/rust/src/rustc-1.0.0-alpha/src/libcore/option.rs:330 
//  ^ this one not entering the println! function

Length 5

stdin

The stdin is a function that could access the standard input (when called, it returns a std::io::stdio::StdinReader type), usage example:

let s = std::io::stdin().read_line().ok().expect("Fatal: read_line failed!");

Or we may type:

use std::io::stdin; // outside function
let s = stdin().read_line().ok()
               .expect("Fatal: read_line failed!");

The .ok() part would check if read_line failed and the .expect("Fatal: read_line failed!") part would exit the program when it does.

Length 4

true

Just like common programming languages, this is a constant with type bool. As you can guess, the other value named false. There are another primitive type in Rust, for example char (32-bit unicode), that can be initialized using single quote. To convert char to string, use .to_string() method.

Length 3

let

The let keyword is the keyword to declare a variable, here's some example on how to use it:

let x = 1;
let (y, z) = (3, 4);
let a : u64 = 18446744073709551610;

The variable defined by let keyword are immutable, to make it mutable, add mut keyword, for example:

let mut b = 123;
b = 234;   

Length 2

""

This is an example on how to create an empty string slices (slice of u8) or &str. This string saved on the program's binary, and cannot be mutated/deleted within runtime. There are another type of string in Rust, a mutable one, that called String. To convert between &str and String use .to_string() method, that copies the old string into another place so it can be modified (mutated). To convert String to &str, use .as_slice() method.

Length 1

1

This an example of valid number literal, to force it as unsigned add a suffix u or _u (uint), some other suffix exists such as i (int), u8, i8, u16, i16, u32, i32, u64, i64, f, f32, and f64.

Factoid

Rust has certain design philosophy:

  • Memory safety must never be compromised
  • Abstraction should be zero-cost, while still maintaining safety
  • Practicality is key

Answered by Kokizzu on November 19, 2021

Awk

Factoid

Awk is a pithy programming language oriented toward string manipulation that also happens to be part of the POSIX standard set of utilities. Awk is named after its original authors, Alfred Aho, Peter Weinberger, and Brian Kernighan. Awk is often used in a pipeline, but large programs have been written in it (pdf, 127KB), too.

0 Characters

Nothing in life is free: an empty awk program prints nothing and exits successfully. (And seems to be the only awk program that doesn't read standard input.)

1 Character

1

An awk program consists of patterns and actions. Omit the action and awk assumes { print }. The above pattern is always true, so awk behaves exactly like cat.

Divergence: Some versions of awk, such as Kernighan's One True Awk consider both the empty string input and the always-true pattern illegal. POSIX says

Either the pattern or the action (including the enclosing brace characters) can be omitted.

So it comes down to whether or not 1 can be considered a pattern.

I'll try to rationalize the divergence between different versions of awk as long as I get more upvotes.

2 Characters

$3

The above pattern is true if the third field has value. If it does, awk will print the whole line. Thus, as a whole awk program, the above will filter all lines that have fewer than three fields.

Once again, the One True Awk does not consider $3 a pattern.

3 Characters

int

BSD treats the above as int($0) and prints every line that can evaluate to a nonzero integer.

Most other awks I tried, including GNU awk consider this invalid. POSIX categorizes int as an arithmetic function and says what it does when invoked without parentheses is undefined.

4 Characters

NF<4

This pattern causes Awk to print those records that have fewer than four fields in them. All editions of awk I tested behave consistently.

5 Characters

/foo/

Boring though it may be, it's time to introduce actual regular expressions. This one will match any line containing the string "foo". This is Awk's bread and butter, and also why it's fairly unnecessary to combine awk and grep.

6 Characters

$NF=NR

This expression overloads the assignment operator = and assigns the number of the current record (row) to the last field. Treating assignments as booleans has the same caveats you might expect from another language. For example $NF=NF would set the last field value to the number of fields, but would skip empty rows.

7 Characters

!(NR%2)

Will print out every other row. It will print the odd ones. I could have written NR%2==0 in the same number of characters, which is more flexible because I could also write NR%2==1 to get the complementary set of rows. I just picked the most obscure syntax because code golf.

8 Characters

!s[$0]++

is one of my favorite Awk expressions. The first time it sees a line it prints it. It never prints the same series of characters again. It's the tersest stable, sort-free uniq I know.

9 Characters

{print$3}

Print the third column. This is one of those boring, but important, Awk "fundamentals" that hopefully opens the door for cooler things with more characters. It's also our first action. (Remember from 1 Character that Awk programs are made up of series of patterns and actions.) Everything heretofore has been just patterns.

13 Characters

FNR<3{print}

Prints the top 2 lines of each file argument. Obviously the print command is redundant, but there were already examples of shorter code. FNR is the line/record number of the current file; whereas NR represents the total number of lines/records processed from all files.

14 Characters

BEGIN{FS=","}

The BEGIN pattern is true before any files have been processed. FS is the field separator pattern used to divide a line/record into fields. This line assigns the field separator before the first file is processed. It is equivalent to executing a script with the command-line argument of -F, with the benefit of not being required to remember to add the argument when running the script.

15 Characters

END{print FNR}

Prints the number of lines/records in the last file read. The END pattern is true after all input has been read, similar to wc -l

Answered by kojiro on November 19, 2021

Perl

Factoid: Though people occasionally stylize Perl as "PERL," it is in fact not an acronym.

Note: This has been relinquished to the community as a wiki. Please feel free to add snippets as you see fit, but please try to retain the formatting used for snippets 1-6 since it looks so clean. :)


Length 27

sub{ $_=shift; lc }->('SE')

An anonymous subroutine: that is, one with no name. This one is followed immediately by ->(...) for its arguments. This snippet also demonstrates a number of other features:

(1) shift acts on an array, lopping off the initial element and returning it; (2) @_ is the array holding all the arguments passed to a subroutine; (3) shift with no arguments, in a subroutine, acts on @_. Thus, the first statement in our subroutine assigns to the variable $_ the first argument passed to the subroutine, in this case 'SE'.

(4) lc returns the lowercasified version of a string (without changing the original variable if the argument is a variable); (5) lc with no arguments acts on $_. Thus, here, lc acts on $_ which is 'SE' and returns 'se'.

(6) If you reach the end of a subroutine (and thus haven't yet returned anything), the subroutine returns the return value of its last statement, if any. Thus, in this case, the subroutine returns 'se'.

Note: Many of these features are very useful in code golf; in real life, for clarity's sake, you will often want to specify the arguments to functions rather than relying on default arguments like $_, and to specify return values of subroutines rather than relying on the return value of the last statement (especially if the last statement is complex).


Length 26

join '', split /W/, $foo;

This demonstrates using a function (with its arguments, or a unary operator) as an argument to another function or unary operator. When, as here, the first function is the final parameter of the other, you usually don't need parentheses to disambiguate. They may be useful for clarity in some cases, but the join... split... construct is so well-known that you don't need parentheses here.

split takes two arguments. (Well, it can take zero to three, but it takes two in this case.) It splits the string $foo along demarcations matching the regular expression /W/, and its return value is a list of the remaining substrings. join puts those back together with the empty string between them. (Incidentally, $foo =~ s/W//g is a simpler way to accomplish the same thing.)


Length 25

sub foo {
    return 1;
}

Our first subroutine! In a later snippet, we'll see how to use arguments (parameters) passed to a subroutine; for now, our subroutine just returns 1 back to whatever called it. Our subroutine is called foo; anonymous subroutines are also possible and will be covered in a later snippet.


Length 24

my $has_nums = $x=~/d+/

See the length-23 snippet. Like that one, this, too, binds $x to a regular expression, and almost the same one. (Like /(d+)/, it looks for a string of digits.) But this one is being assigned to $has_nums rather than to a list, so it's being called in scalar context. The binding operator =~ in scalar context, when the right-hand side is /.../, returns 1 (which is true) or the empty string (which is false) depending on whether the match succeeds. So now you can use $has_nums in if $has_nums, for example. (What =~ returns in scalar context is different if its right-hand side is s/.../.../ or some other things.)


Length 23

my ($num) = $x=~/(d+)/

This demonstrates =~, called the binding operator. It binds (in this case) $x to the regular expression /(d+)/. Like just about everything in Perl, this operator returns something, and what it returns depends on what context it's called in. Assigning the binding operator's return to a list ($num) is calling it in list context. The binding operator in list context, when it's binding to just a regular expression /.../, returns the list of matches to the stuff in parentheses in the regular expression, which in this case is d+, a string of digits. So $num is assigned to the first string of digits within $x. (What =~ returns in list context is different if its right-hand side is /.../g or s/.../.../ or other things.) See also the length-24 snippet.


Length 22

$x = 1==0 ? 'a' : 'b';

... ? ... : ... is the ternary operator. It has precedence over comparison operators like == but not over assignment operators like =, so the above means the same as $x = ( (1==0) ? 'a' : 'b').


Length 21

if ($x) {
    # ...
}

This demonstrates Perl comments, which are from # to the end of the line, and the common practice of indenting four spaces for clarity. (There are other ways to comment, too, but those will have to wait for a later snippet. This snippet also tests $x for truthiness, but truthiness, too, will have to wait.)


Length 20

next LBL if $x >= 0;

This demonstrates Perl's use of postfix if. (It means the same as if ($x >= 0) {next LBL;}.) Postfix control-flow statements are usually (outside of golfing) reserved for things like next and last and warn and die where the point of postfixing is to draw attention to the crucial command being conditionally executed.


Length 19

$_ = 'quux';
print;

This demonstrates Perl's use of a default input for (many) built-in functions. If you don't say what you want to print (or lcfirst or sqrt or split or…), Perl will do it to $_. (The same is true for binding to a pattern match, and $_ is the default scalar used in other circumstances also — but those will have to wait for a later snippet.) For clarity and to ensure you're using the variable you think you're using, it's often best to use some variable other than $_.


Length 18

@hsh{'Ann', 'Bob'}

This is a hash slice. As in the Length 17 note, below, the {...} (rather than [...]) signifies that %hsh is a hash. And the @ sigil here signifies we're making a list of our hash values. Which hash values? The ones with the keys listed. So if %hsh is ('Ann' => 123, 'Bob' => 345, 'Cam' => 567) then @hsh{'Ann', 'Bob'} is (123, 345).


Length 17

$ary[0] = $hsh{a}

$ is the sigil for a scalar. But an element of an array, or a value of a hash, is a scalar. So even though may call an array @ary and a hash %hsh, their values are $ary[...] and $hsh{...}. The type of bracket indicates whether it's an array or a hash.


Length 10

print$x=<>

This is a “one-line cat” program: it outputs one line of its input, then exits. It demonstrates several features of the language. The null filehandle is used again, now to assign a line of input to the variable $x. This assignment also returns the value, which is then printed to STDOUT. But wait! Didn't <> return the whole file in Snippet 7, not just one line? Perl statements know about the “context” they're evaluated in. In “scalar context”, <> reads one line. In “list context” it reads (“slurps”) the whole file at once; the result is a list with one element for each line. print provides a list context (and concatenates its argument list), but assignment to the scalar variable $x enforces scalar context.


Length 7:

print<>

This, like cat, prints back its input. The <> is the “null filehandle”; its lack of a name means that it reads from the “magical” filehandle ARGV, which sequentially opens and reads from filenames given as line arguments, or STDIN if there are no arguments (just like cat does). In the full form, the filehandle goes between the angle brackets: <FILEHANDLE> may also be spelled readline(*FILEHANDLE).


Length 6:

Int $x

Perl 5 is all dynamic typing. But Perl 6 supports both static and dynamic typing! It's one of the many ways in which the two versions have diverged.


Length 5:

'$x'

This may seem trivial but it's something that can confuse people new to Perl who are familiar with other languages. In some languages, it doesn't matter whether you use single or double quotes. It does in Perl, though. If you have a variable $x equal to 5, "$x" returns "5" and '$x' returns '$x'. Perl interprets things in double quotes but uses anything in single quotes literally.


Length 4:

less

The Perl pragma to use less of something, available in CPAN. Examples include use less 'fat'; for those on a diet, or use less 'CPU'; for those whose computers are on diets. The class method less->of('x') will tell you if use less 'x'; was specified. Unless you take advantage of that class method in some way, specifying use less is useless. (See what I did there?)


Length 3:

use

Perl is extensible via modules, which are loaded using use. Other things use use too. Show self-discipline; use strict; use warnings; in your programs.


Length 2:

$!

Oh no, something has gone wrong! The program has died, be it intentionally (via die) or by the will of Zeus. But why oh why has execution stopped? At last, $! rides the Perl camel to the rescue. It contains the error code. (There's also $@, which contains the error message.)


Length 1:

;

Like so many other 1 character answers here, ; is a valid Perl statement which does nothing. On its own it's about as useful as vacuuming a block of tofu.

Answered by Alex A. on November 19, 2021

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.

Answered by joojaa on November 19, 2021

μ-recursive functions

These come in many flavors, but are all essentially the same: a "functional assembly" of sorts.

Factoid: μ-recursive functions are a Turing-complete model of computation that, unlike Lambda calculus (which is theoretically equivalent to it) has no more-or-less popular language based on it. Why? Because it manages to combine the readability of (((((Lisp)))))) with the eloquence of assembly. However, there are interpreters for several langauges that are actually flavors of μ. None of them, however, can operate with anything but unsigned integers. Pity.

μ, by default, supports only 2 datatypes - an unsigned integer and a function. Operators recieve and return functions, functions recieve and return unsigned integers. Simple and straightforward. That's all there is to the entire language.

If this recieves enough upvotes, I'll be providing snippets in RF, a small language based on μ-recursive functions created for educational purposes by a teacher at a university where some friends of mine study. It uses a flavor of μ that is a bit different from Kleene's. You can download it here: http://www.mediafire.com/download/fnsyze4crthgl89/rf_setup.rar (warning: entire interface is in Russian; function definitions go into the top text field, function calls go into the bottom left one, results get output to the bottom right one).

Length 1 snippet:

N

This is not runnable code, sadly. I'd need at least 5 upvotes for the first runnable RF snippet.

This is one of the 3 built-in functions supported by μ, the successor function. What does it do? Well, it simply takes one number as an input and returns this number + 1. It's also sometimes abbreviated as s in different μ languages.

Length 3 snippet:

f()

This is the shortest possible "input" call of a μ-recursive function. It calls a 0-ary (parameterless) function f with, well, no parameters.

As μ is a 100% pure functional language, input is restricted to function calls, and output is restricted to function return values. All μ-based languages, including RF, provide a way to list the function calls that the program should recieve as "input". Note that this specific example won't run in RF because it requires function calls to have a ; at the end, but it could run in another μ-based language.

Length 4 snippet:

M(O)

This is one of μ's 3 operators: the minimisation operator, sometimes abbreviated as μ. Obviously, it gives the model of computation its name. This specific snippet synthesizes and returns a 0-ary function that always returns 0.

Now, this calls for a little bit of theory.

What does this operator do? Its workings can be written concisely as follows:

M(f(a1, a2, ... an-1, an)) called with arguments (a1, a2, ... an-1) returns the least value of an satisfying the condition f(a1, a2, ... an-1, an) == 0

It takes an n-ary function f as input, and synthesizes and returns an n-1-ary function (i.e. taking one argument less than the input function).

What does the returned function do? When called with some arguments (a1, a2, ... an-1), it forwards them to the input function f. It then finds the least possible (i.e. starting from 0) value of the last argument (an) which, together with the forwarded arguments, will make f return 0. If f doesn't ever return 0 in these conditions - hello, endless loop. If it does, the synthesized function returns the value of an it found.

In the snippet above, the operator takes the 1-ary built-in function O, and synthesizes a 1 - 1 = 0-ary function which finds and returns the least value of the last (and, in this case, the first) argument that would make O return 0. As O happens to always return 0, the least value of the argument would be 0. That is what the synthesized function will return.

Interesting note: there are two main different notation for this, as well as the other operators. Kleene, for example, uses a notation that is the inverse of the one RF uses: in his texts, an is actually the first argument of the input function f, not the last one. However, this doesn't really matter.

Length 5 snippet:

O(1);

I promised a runnable RF snippet, now, here you go. This is a RF function call "input". It calls the built-in 1-ary function O mentioned in the previous snippet, which always returns 0, no matter what you pass to it. It can be really, really useful at times.

Length 6 snippet:

I[1,2]

This is the identity function, one of the 3 built-in functions. It can take several arguments and return one of them. It is defined as I[i,n](a1, a2, ... an) = ai

You can think of it as a function "template" of sorts. The square brackets can take 2 constant (nonzero unsigned integer) parameters, which determine the identity function's behaviour. The second parameter in the brackets is the number of the function's actual parameters. The first one is the index, starting from one, of the parameter that the function returns. For example, the function shown above can be read as follows: "define a function which takes 2 parameters and returns the 1st one".

Length 7 snippet:

S(N,O);

We finally reached another operator! S is the superposition operator. The piece of code above uses it to create an 1-ary function that always returns 1.

This operator can be expressed as follows: S(f0, f1,f2, ... fn) called with arguments (a1, a2, ... am) = f0(f1(a1, a2, ... am), f2(a1, a2, ... am), ... fn(a1, a2, ... am))

At least 2 functions should be supplied to the operator. f0, the first function, should have an arity equal to the number of functions passed to the operator besides it (i.e. for f1,f2, ... fn, the arity of f0 should be n). It cannot be a 0-ary function. All other functions passed to the operator should have an equal arity (i.e. f1,f2, ... fn should all have the arity m). The synthesized function shall also have this arity (m).

The synthesized function first calls all but the first of the operator's argument functions with the arguments passed to it, and then calls the first of the operator's argument functions with the others' return values and returns its result.

In the snippet above, for example, when we pass an argument to the created function, it calls O with this argument, which returns 0. Then it calls N with this return value, which returns 0+1 = 1, so the synthesized function also returns 1.

Length 8 snippet:

zo=M(O);

This is a function definition! You can call it with zo();. It defines the zero-arity (parameterless) function returning 0 that I already discussed above.

Now we're getting to the fun part, recursion!

Length 15 snippet:

f=R(zo,I[2,2]);

Here zo is the previously defined (length 8 snippet) function.

R is the recursion operator. The above snippet defines a recursive function that takes one input parameter, decrements it until it reaches zero, then returns zero.

This operator can be expressed as follows: f = S(f0, f1) called with arguments (a1, a2, ...a{m-1}, am) = if am > 0: f1(a1, a2, ... a{m-1}, am - 1, f(a1, a2, ... a{m-1}, am - 1)); if am == 0: f0(a1, a2, ... a{m-1}).

This is basically good old tail recursion, plain and simple.

Let's see how the function above works for a parameter x: first, we have f(x). If x > 0, we return I[2,2](x - 1, f(x - 1)), which is the same as f(x - 1), and so on until we reach f(0), in which case we return zo(), i.e. 0.

The recursion operator is very important in μ-recursive functions, it's the backbone of most of the logic. However, some of its uses may seem a bit strange:

Length 16 snippet:

de=R(zo,I[1,2]);

This function takes one parameter x and returns x - 1 (decrements), if x > 0, and returns 0 if x == 0. Implementing it as a counterpart to N is instrumental in implementing subtraction (just as N is necessary in addition).

This use of the recursion operator may be considered strange because, well, there's actually no recursion going on here at all! Consider: if x > 0, de(x) = I[1,2](x-1, de(x-1)), equivalent to simply x-1, so the tail call de(x-1) doesn't even happen! And if x == 0, it simply returns zo(), or 0.

Length 18 snippet:

de3p=S(de,I[3,3]);

I see we didn't have an example for the superposition operator already, but here we go now. This defines a function de3p which, using the previously-defined de, takes 3 parameters and decrements the last one (calling it as de(I[3,3](x,y,z)) = de(z), where x, y and z are the 3 parameters).

Using this function, we can now define subtraction!

Length 19 snippet:

sub=R(I[1,1],de3p);

The sub function takes two parameters, x and y, and returns x - y. How it does that is quite obvious: if y > 0, sub(x,y) = de3p(x,y-1,sub(x,y-1)) = sub(x,y-1) - 1. And if y == 0, sub(x,y) = I[1,1](x) = x. So, basically, the function calls itself until y is 0, then takes x and backtracks for y steps, subtracting 1 from x on every step, resulting in x - y.

Length 20 snippet:

next3p=S(N,I[3,3]);

I decided to show a runnable example with every built-in function and operator; this is the last one, the built-in function N. This defines a function next3p, which takes 3 parameters and increments the last one by 1: next3p(x,y,z) = z + 1. This is pretty much by analogy with the previous example and doesn't really need an explanation.

Now, using this example, we can do addition!

Length 21 snippet:

ad=R(I[1,1],next3p);

This defines a function ad which takes 2 parameters and adds them together. It works the exact same way as the subtraction function, the only difference being that 1 is added to x on every backtracking step.

Answered by Mints97 on November 19, 2021

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*

Answered by Mints97 on November 19, 2021

JavaScript, EcmaScript 6

I will be focusing on features/snippets of/from ES6 standard in this answer. Some snippets require knowledge of topics previously presented, so you may want to read this bottom-to-top.

Length 17 snippet:

"?".codePointAt()

More Unicode support! .codePointAt() is a Unicode-compliant version of .charCodeAt(). For example, if you were to take

"?".charCodeAt()

you would find 55362. This might seem right, but if you convert it to hexadecimal, you would find that it corresponds to U+D842. Looking on Graphemica, we can see that the character is actually U+20BB7. U+D842 is one of the two surrogates that makes up the UTF-16 representation of that character.

But enough of these details: the point of .codePointAt() is to find the actual Unicode point of the character. "?".codePointAt() is 134071, or U+20BB7—the correct result. Finally Unicode lovers can use JavaScript!

Length 16 snippet:

/^.$/u.test("?")

Another nice feature of ES6 is proper Unicode support! If you tried this code in ES5:

alert(/^.$/.test("?"))

You might be surprised to find that the answer is false! The problem here is in JavaScript's default encoding, UTF-16: characters above U+FFFF are actually represented as 2 chars, called "surrogates". (You can learn more about this on Wikipedia.) In order to fix this, you need a more complex regex:

alert(/^(?:[uD800-uDBFF][uDC00-uDFFF]|.)$/.test("?"))

ES6 introduces the u flag on regexes. When u is set, characters above U+FFFF are still captured as a single char. So /^.$/u.test("?") returns the correct result: true.

Length 15 snippet:

String.raw`qn`

Back to tagged templates! ES6 comes with a function all set up to be used as a tag: String.raw. This returns the raw text you typed in the template (replacing interpolations with their values), so the above snippet is equalivalent to "q\n".

Length 14 snippet:

Number.EPSILON

As you may know, JavaScript's numbers are not arbitrary-precision; they have exactly 53 bits of precision. This can cause problems when trying to add decimal numbers:

var point3 = 0.1 + 0.2;
alert(point3 === 0.3); // false!

The problem here is that neither 0.1 nor 0.2 can be represented exactly in binary, and when adding them together, the least significant bit is rounded the wrong way, resulting in 0.30000000000000004 instead of 0.3.

Number.EPSILON was added as a workaround to this problem; it is equal to 2-53, the smallest number that can be added to 1 without rounding back down to 1. We can use this to create a new equals function:

equals = (num1, num2) => Math.abs(num1 - num2) < Number.EPSILON;

alert(equals(point3, 0.3)); // true!

Hooray for ES6!

Length 13 snippet:

s=>s.split` `

What is this? A function call without parentheses? Actually, it's another use of template literals: tagged templates! But what is actually happening here?

When you tag a template with a function, it calls the function as usual, but it passes in the arguments a little differently. Take this example function:

function parseMe(strings, name, age) {
  alert(`Your name is ${ name } and you are ${ age } years old`);
  console.log("We don't need these strings:", strings);
}

myName = "Bob";
myAge = 123;
parseMe `Hello, I'm ${ myName } and I've orbited the earth ${ myAge } times.`;

This alerts Your name is Bob and you are 123 years old. Why? When calling a function with a tagged template, JavaScript passes each ${ } value as a separate parameter, groups the strings into an array which is passed before everything else. So you're really calling parseMe like this:

parseMe( ["Hello, I'm ", " and I've orbited the earth ", "times."], myName, myAge );

Cool, right? Now back to the original snippet. Now we can see that it could be written like this:

s=>s.split([" "])

.split coerces its argument to a string before splitting. The string representation of [" "] is " ", so the function could be written yet another way:

s=>s.split(" ")

And this simply splits the text on spaces, which splits it into words. Isn't ES6 awesome?

Length 12 snippet:

n=>`Hi
${n}`

Introducing...template literals! Yet another super-helpful ES6 feature. These act like strings for the most part, but you can include newlines without escaping them. Not only that, but you can also use interpolation! If you run the above function with input "JavaScript", it will output this:

Hi
JavaScript

Length 11 snippet:

[a,b]=[b,a]

Tired of using that old var tmp = a; a = b; b = tmp; trick to swap variables? Now you don't have to! Using destructuring, you can swap those two variables quickly and concisely with the above statement.

Length 10 snippet:

[a,...b]=b

Destructuring! Yay! This is one of the cooler features of ES6. You can use it to do many things that would have taken a lot more bytes in ES5. For example, this is what the above statement corresponds to in ES5:

a=b[0],b=b.slice(1)

Actually, a=b.unshift() works too, but consider when you want to grab the first three items:

[x,y,z,...b]=b
x=b.unshift(),y=b.unshift(),z=b.unshift()

Or if you don't want to change the value of b:

[x,y,z]=b
x=b[0],y=b[1],z=b[2]

As you can see, destructuring is shorter, more readable, and just all-around better.

Length 9 snippet:

new Set()

Another useful data-type that JavaScript now supports is Sets! You can create a set like so:

var myArray = [1, 3, 6, 3, 2, 1];
var mySet = new Set(myArray);
// Set [ 1, 3, 6, 2 ]

As you can see, creating a Set out of an array removes all duplicate items. You can turn it back into an array with the spread operator:

myArray = [...mySet];
// [ 1, 3, 6, 2 ]

You can also use this trick on strings:

var myString = "Hello, World!";
var mySet = new Set(myString);
myString = [...mySet].join("");
// "Helo, Wrd!"

Keep in mind that the Set constructor must be called with new, and only works on the first argument. For example, this won't work:

var mySet = new Set(1, 3, 6, 3, 2, 1);
// TypeError: 1 is not iterable

You can learn all about Sets on this page.

Length 8 snippet:

(i=0)=>i

You probably understand what this example is: default parameters! JavaScript ES5 is really horrible with default values. Usually you can get away with this workaround:

function f(i) {
  i = i || 0;
  return i;
}

However, this resets i if it is anything falsy (false, 0, "", null, or undefined). To just do null or undefined, you have to be much more verbose:

function f(i) {
  if (typeof i === "undefined" || i === null)
    i = 0;
  return i;
}

But ES6 contains a new syntax for default values! Now you can shorten your code to this:

function f(i = 0) {
  return i;
}

Or in ES6 arrow notation, f=(i=0)=>i. When given an input, this just returns the input, but when called with no input, it returns 0. This is very helpful in uncountable scenarios, and possibly one of the best additions of ES6.

Length 6 snippet:

Symbol

JavaScript now supports Symbols! A symbol is created with Symbol("foo"), and every symbol created is different: Symbol("foo") !== Symbol("foo") The only way to keep a symbol is to assign it to a variable: var sym = Symbol("foo"); sym === sym

One of the most useful Symbols is Symbol.iterator. This is a Generator which is used whenever you iterate over an object, whether with for-in loops or the ... operator (see below). For example, the following code defines an iterator for all Number objects:

Number.prototype[Symbol.iterator] = function* () {
    for(var i = 0; i < this; i++)
        yield i;
}

Now [...6] returns [0,1,2,3,4,5]! Aren't generators fun?

Length 5 snippet:

const

This for a change is exactly what you've guessed! Its a new variable declaration syntax used for creating constant variables.

const a = "foo";

Now a's value is fixed, any attempt to change it will lead to a SyntaxError (cos JS!). Not only that, if you skip the assignment part while declaring the variable, that will also lead to a SyntaxError.

const a;
// Exception: SyntaxError: missing = in const declaration

const a = "foo";
a = "bar";
// Exception: SyntaxError: invalid assignment to const a

Length 3 snippet:

...

Default arguments ? Java ? Nope! This is the new spread operator and it does exactly what it says.

For instance, you want to spread your array variable A into another array B in the middle alongside other things:

var B = [1, 2, 5, ...A, 8, 0];

That simple!

You can even do this with function calls or arguments.

function foo(a, b, ...c) {}

is a function whose first argument goes in a, second goes in b and rest all arguments (third, fourth ...) go in as an array in c.

Now if you want to call that function and all your arguments are in the array A, you can do it like

foo(...A);

Length 2 snippet:

=>

Think that I put greater than or equal to sign the wrong way ? Think again! Think ES6!

This is one of the best features of ES6 - Fat arrow function . Apart from reducing a lot of bytes while defining a function (var a=_=>_+_ instead of var a = function(_){return _+_}), arrow functions also change the behavior of this so that you don't have to bind the function again and again.

Length 1 snippet:

*

Multiplication ? Nope! Remember ES6! The * keywords is part of one of many syntax sugar + features of ES6 - Generators. This is added to the function keyword to make the function a generator function.

Factoid

ES6 adds a lot of useful syntax sugar and features into the language inspired by a lot of other languages.

The most useful fact about ES6 is that due to the added syntax and features, it performs much better than ES5 (current generation JS across all browsers) in terms of .

The final spec for ES6 was finalized in June 2015, and all major browsers (except IE) have enabled most of the new features. You can check this page to see which features your browser supports, as well as all major browsers and other environments.

Answered by Optimizer on November 19, 2021

x86 Machine Code

Factoid:

x86 Machine Code is the assembled version of x86 Assembly that the processor actually runs. It was developed back when memory and storage space were expensive, and was designed to be somewhat backwards compatible all the way to the Intel 8008. Keeping executable code small was one of the goals, and it utilizes variable length instructions and a CISC architecture to help achieve this (which has had the drawback of making it more complicated to improve performance on modern processors). This, along with the bare-bones nature of assembly and machine code in general, gives x86 programs the ability to be extremely compact.

Length 1:

Now for the first program:

0xC3

Open up a hex editor, enter that byte, and save it as test.com.

You now have valid MS-DOS program which immediately returns without doing anything, since 0xC3 is the instruction 'RET'. This does however show another interesting aspect for golfing with x86: the .com file format. This executable format has absolutely no header - the file is simply loaded into memory starting at address 0x100, and then execution is started at 0x100. This means no bytes wasted on metadata!

Length 2:

Our next program:

0x4D 0x5A

or 'MZ' in ASCII.

Ok, I cheated a bit, that really isn't a useful program, since it corresponds to the instructions

DEC     BP
POP     DX

Which aren't actually useful for starting a .com program. In fact, that's the whole point of those two values - no reasonable .com file should start with them! .com files were limited to 65280 bytes in size (64KiB - 0x100), so when larger programs started to be needed, a new format had to be developed. This was the .exe file format, which does have a header. However, MS-DOS needed to keep the .com extension on certain components for backwards compatibility, so it needed a way to detect whether a .com file was really an .exe. They chose the sting 'MZ' as this magic number, and to this day, if you open up a Windows .exe (or .dll) file in a hex editor, you'll see they start with those two bytes. It amuses me that even the most modern Windows program starts with a compatibility constraint from the 70's.

Length 3:

Now for an infinite loop:

41 E2 FD

Which translates to

start:
inc cx
loop start 

This program increments the value of CX (which will be >0 to begin with), then executes the loop instruction. Loop is an excellent example of a CISC instruction since it combines 3 simple operations into one special-purpose operation: it decrements the value of CX, checks if it is 0, and jumps to the target label if not. There are also forms of loop that check other flags in addition to ending when CX is 0. We could have done just 'jump start' for a 2 byte infinite loop, but this was more interesting.

Length 4:

A program that is minimally useful:

40 CD 10 C3

Translated to assembly:

inc ax    ; 1 byte
int 10h   ; 2 bytes
ret       ; 1 byte

This program sets the console to 40x25 characters, clears the screen, then returns to the command line. AX is set to the video mode we want (1), then the BIOS interrupt 10h is called to actually set the video mode & clear the window, before returning. Expect to see more of these BIOS interrupts in the future.

Length 5:

We can now implement a pause program:

B4 01 CD 21 C3

Translated to assembly:

mov ah,1  ; 2 bytes
int 21h   ; 2 bytes
ret       ; 1 byte

This program tells the BIOS to wait for a key to be pressed and echos it to the screen before returning. This also demonstrates how on the x86, some of the registers can be partially read or written. In this case, we set the top byte of AX (AH) to 1. On 32 bit processors, you can also operate on the low 16 bits without affecting the top 16 bits. This ability to modify partial registers can be handy for assembly programmers, but has drawbacks for modern processors trying to perform out-of-order execution, since they can introduce false data dependencies.

Length 9:

Now to actually display output:

68 00 B7 07 AB 40 79 FC C3

Translated to assembly:

; These two instructions set up ES, the 'extra segment'
push 0xb700 ; 3 bytes
pop  es     ; 1 byte
label:
stosw       ; 1 byte, Store Word - Copy AX to [ES:DI] then add 2 to DI
inc  ax     ; 1 byte
jns  label  ; 2 bytes, Jump Not Signed - Jump unless the sign flag is set (when inc AX yields 0x8000
ret         ; 1 byte

The output is the default character set repeated in different colors. The low byte of AX is the character code, and the high byte specifies the colors to use. Default character set repeated in different colors

16 bit programs could only address up to 64KiB directly. To get around this, the x86 used 'segments' - special registers that would be multiplied by 16 and added to all memory accesses to give 20 bits of addressable memory. A program could change the values of these segment registers in order to access more memory - or special areas of memory: this program modifies the extra segment in order to write to video memory. Different types of memory access used different segment registers, allowing code, data, and the stack to be accessible in different chunks of memory at the same time. The default segment could also be overridden for many instructions.

Length 20:

Let's make something recognizable - we will use 'Rule 90' to draw Sierpinski triangles.

B0 13 CD 10 68 0F A0 1F AC 31 C2 88 94 3E 01 87 D3 93 EB F4

In assembly:

mov al,13h      ; 2b
int 10h         ; 2b - Set the video mode to 13h

push    0xA00F  ; 3b
pop     ds      ; 1b - Set the data segment to video memory

start:          ; This loop runs 'Rule 90' to draw Sierpinski triangles
lodsb           ; 1b - load al with [ds:si] then increment si

xor     dx,ax   ; 2b - xor the left and right values of the previous row of pixels
mov     [si+318],dl ;4b - store result to memory

xchg    dx,bx   ; 2b - swap register values
xchg    ax,bx   ; 1b - swapping with ax is 1 byte shorter

jmp     start   ; 2b - infinite loop

Sample output: Sierpinski Triangles

For this program, we use the somewhat famous 'Mode 13' - a graphics mode that has a resolution of 320x200 with 256 colors. It was used by many popular DOS games, such as Doom.

Length 21

Let's see who manufactured the CPU we're running on.

0F A2 66 60 BB EE FF B9 0C 00 8A 17 43 B4 02 CD 21 E2 F7 FF E1

Translated to assembly:

cpuid         ; 2b  CPU ID - retrieve processor information based on the value in AX. For AX=0,
              ;     the 12 bytes in EBX, ECX, and EDX are loaded with a vendor identification string
pushad        ; 2b  Push all registers on the stack (32 bit version)
mov  bx,0xffee; 3b  Start of the vendor identification string on the stack
mov  cx,12    ; 3b  12 characters to print
print:    
mov  dl,[bx]  ; 2b  Character to print
inc  bx       ; 1b  Advance string position
mov  ah,2     ; 2b  Set AH to the 'Print character to STDOUT' value
int  21h      ; 2b  Call the bios interrupt to print
loop print    ; 2b  Decrement CX and jump if it is not zero
jmp  cx       ; 2b  Instead of restoring the stack, just jump right to the exit point

Sample output:

c:misc>cpuid.com
GenuineIntel

This program uses the CPUID instruction to get info about the processor it is running on, in particular, the vendor identification string. Most people will see 'GenuineIntel' or 'AuthenticAMD', unless they have an uncommon CPU manufacturer or are running in certain virtual machines.

Length 26

We can now do interesting animations

B0 13 CD 10 C4 07 BB 40 01 59 99 89 F8 F7 F3 31 D0 AA E2 F6 26 FE 05 47 EB FA

In Assembly

mov al,13h     ;2b
int 10h        ;2b Enter Video Mode 13h

les ax,[bx]    ;2b Set ES to (roughtly) video memory
mov     bx,320 ;3b Set up  BX asdivisor
pop     cx     ;1b Zeroize CX

start:
cwd            ;1b Sign extend AX to DX, AX will never have the sign bit set so this zeroizes DX in 1 byte
mov     ax,di  ;2b Copy video memory pointer
div     bx     ;2b Divide by width to get AX = Y pos, DX = X pos
xor     ax,dx  ;2b X pos ^ Y pos
stosb          ;1b Store and increment video pointer
loop    start  ;2b CX starts at 0, so this will loop until it wraps around

cycle:
inc     byte [es:di];3b Increment value in video memory to animate
inc     di     ;1b Increment video memory pointer
jmp     cycle  ;2b Infinite loop 

And the output will look like this:

Marching XOR

The function X pos ^ Y pos produces an interesting fractal, especially when animated

Length 27

Not only can you generate text and graphics in a small x86 .com program, you can also generate sound and music:

BA 31 03 B0 3F EE BA 30 03 B0 93 EE B4 01 CD 21 3C 1B EE 3C 1B B0 7F EE 75 EC C3

In assembly:

    mov dx,0x331            ; value for the midi control port
    mov al,0x3F             ; command value to set midi mode to UART
    out dx,al               ; output the command to the midi control port
play_loop:
    mov dx,0x330            ; value for the midi data port
    mov al,0x93             ; midi instrument value (piano)
    out dx,al               ; output to midi data port
    mov ah,1
    int 0x21                ; read character from stdin, with echo
    cmp al,27               ; test if it is escape
    out dx,al               ; output the ascii value as the midi note to play
    mov al,0x7F             ; note duration
    out dx,al               ; output note duration
    jne play_loop           ; loop if escape was not pressed
    ret  

This program uses the midi card to turn the keyboard into a piano. To do this, the midi card is set to UART mode, which plays midi notes as soon as they are received. Next, the program waits for a character to be pressed, and outputs the ASCII value as a note to the midi card. The program runs until escape is pressed.

Length 29

Let's use an iterated function system to generate a Dragon Curve fractal:

B0 13 CD 10 89 D0 01 CA 29 C1 D1 FA D1 F9 73 03 83 E9 7A B4 01 CD 16 B8 02 0C 74 E6 C3

Translated to assembly:

mov  al,13h
start:
int  0x10    ; This does double duty, setting the video mode to 13h at program start,
             ; and calling the 'draw pixel at coordinates' interrupt when looping
mov  ax,dx   ; The next couple instructions are our IFS, the algorithm is aproximately
add  dx,cx   ; f(y) = 0.5x + 0.5y
sub  cx,ax   ; f(x) = 0.5x - 0.5y OR f(x) = 0.5x - 0.5y - 1
sar  dx,1    ;
sar  cx,1    ;
jnc  skip    ; This jump handles pseudo-randomly switching between the two functions for x,
             ; based on if the previous value of x was odd or not.
sub  cx,122  ; Magic number, chosen since it provides sufficent 'randomness' for a filled in
             ; fractal and a good scale to the fractal. 102 and 130 also work.
skip:
mov  ah,1
int  0x16    ; Get keyboard state, zero flag will be set if no key has been pressed
mov  ax,0xC02; Set up AH for the draw pixel function when int 0x10 is executed,
             ; AL = color, CX = column, DX = row
jz   start   ; Loop if a key hasn't been pressed
ret  

Output:

Dragon Curve

Pressing a non-control key will cause the program to exit. This is based off of Fire Coral by Desire on Pouet.net.

Length 52

This program is a bit of a double feature, it shows a bit of the x87 floating-point co-processor, and self-modifying code.

B3 07 D9 E8 B1 11 DE 0E 32 01 E2 FA BE 0A 24 56 B1 09 DF 34 AC D4 10 
86 E0 05 30 30 50 E2 F5 44 B4 2E 50 89 E2 B4 09 CD 21 FE 06 03 01 4B
75 D2 CD 20 0A 00

When run, the program will output several mathematical constants:

1.00000000000000000
3.32192809488736235
1.44269504088896341
3.14159265358979324
0.30102999566398120
0.69314718055994531
0.00000000000000000

These are One, Log2(10), Log2(e), Pi, Log10(2), Log e(2), and Zero.

In assembly:

org 100h

mov     bl,7         ;Counter for the total number of constants to print
start:
fld1                 ;Floating point constant to load on the FP stack,
                     ;start with 1 since it's op-code is the lowest

mov     cl,17        ;Multiply the constant by 10, 17 times to get the
mult:                ;printing part as an integer
fimul   word[ten]
loop    mult

mov     si,10+'$'*256;ASCII new line (10) and the end-of-string ($)
                     ;characters. These are used both as
push    si           ;a constant memory location, and stored to the
                     ;stack to format and printing

mov     cl,9         ;print 18 digits (9 pairs)
fbstp   [si]         ;store the integer part of the floating point
                     ;number on top of the FP stack as a packed
                     ;binary-coded decimal number (1 digit/nibble),
                     ;and then pop the number off the FP stack

convert:
lodsb                ;load a pair of packed digits

db 0xd4,16 ; AAM 16  ;ASCII Adjust For Multiply instruction using
                     ;non-standard base 16. This puts AL/16 in AH,
                     ;and AL%16 in AL, unpacking the digit pair.

xchg    ah,al        ;Swap the digit order
add     ax,'00'      ;Convert the digits to ASCII values
push    ax           ;Store digits on the stack
loop    convert

inc     sp           ;AX now holds the 1st 2 digits to print,
mov     ah,'.'       ;so to insert a decimal point, the 2nd digit
push    ax           ;is replaced with a '.', the stack pointer
                     ;is adjusted to overwrite 1 byte, and then
                     ;AX is pushed on the stack

mov     dx,sp        ;Load DX with the start of the print string
mov     ah,9         ;Load AH with the 'Print String' constant
int     21h          ;Call the 'Print String' interrupt to display
                     ;the constant

inc     byte[start+1];Self-modifying code - increment the load
                     ;floating point constant op-code to iterate
                     ;through all of them

dec     bx
jnz     start        ;Exit when all 7 constants have been printed
int     20h


ten: dw  10

Floating point math on x86 systems was originally handled by the optional x87 co-processor, it wasn't until the 486 that it was moved onto the same chip. The x87 also had a rather different architecture, it was stack-based, with 8 80bit registers available. It also had a variety of rounding modes, precision, and maskable exceptions that could be set.

This program prints the values for seven constants baked into the processors. It may seem odd that instruction space would be wasted on simple constants like 0 and 1, but keep in mind that the instruction set was created when memory was small, and these instructions are typically 2 bytes smaller than equivalent operations. The program also uses an obscure instruction, FBSTP -'Store BCD Integer and Pop'. Back when the x86 was developed, operations on BCD numbers were more common, and the x86/x87 has several instructions specifically to simplify BCD math, such as the AAM 'ASCII Adjust for Multiple' instruction also used in the program.

In the unprotected memory model used by early x86 programs, there is no distinction between data and code. Because of this, it is easy to iterate through the sequentially encoded 'Load Constant' instructions by simply incrementing the appropriate value.

Length 64

Cross-posting my entry for the Mandelbrot Challenge, a program can be written that displays a 320x200 color Mandelbrot fractal in only 64 bytes.

B0 13 CD 10 C4 07 99 89 F8 B9 40 01 F7 F1 83 E8 64 FE CE 31 DB 31 F6 
89 F5 0F AF F3 01 F6 0F AF DB 70 19 0F AF ED 70 14 01 EB 70 10 29 EB
29 EB C1 FB 06 01 D3 C1 FE 06 01 C6 E2 DB 91 AA EB C6

In assembly:

mov al,13h ; set up graphics mode 13
int 10h

les ax,[bx]; trick to set video memory

FillLoop:
cwd
mov ax,di  ; di is the current position on screen
mov cx,320 ; convert di int x,y screen coordinates
div cx     ; CX is the iteration counter, exit the loop if it hits
           ; zero before the value escapes.
sub ax,100 ; center the fractal vertically
dec dh     ; center the fractal horizontally

xor bx,bx
xor si,si

MandelLoop: ; Fairly standard Mandelbrot routine,
mov bp,si   ; exits if the values overflow
imul si,bx
add si,si
imul bx,bx
jo MandelBreak
imul bp,bp
jo MandelBreak
add bx,bp
jo MandelBreak
sub bx,bp
sub bx,bp

sar bx,6   ; We use fixed point math with the lowest 6
add bx,dx  ; bits being the fractional portion, so this
sar si,6   ; rescales the values after multiplication
add si,ax

loop MandelLoop

MandelBreak:
xchg ax,cx ; Write the escape itteraction as the color
stosb
jmp FillLoop

The end result is this image:

Mandelbrot Fractal

This program uses fixed-point math to generate the fractal, since it takes fewer bytes. The lowest 6 bits of the 16 bit registers is considered to be the fractional part of the number, and the values are rescaled after being multiplied.

Answered by Sir_Lagsalot on November 19, 2021

아희(Aheui)

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

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


Factoid

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

You can try programs below at here.


Length 1

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

Explanation

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

Length 2

아희

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

Explanation

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

Length 3

밯망희

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

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

Explanation

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

Length 4

박빠나망

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

Explanation

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

Length 5

바뱍멍다뼈

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

Explanation

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

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

바박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망...

Answered by Snack on November 19, 2021

KSFTgolf

I've finally finished at least a very early version of an interpreter for my golfing language KSFTgolf. It probably doesn't work very well, but I'm hoping to make it better by adding instructions that would help to solve problems here. I'll probably be updating it several times while this is posted. I'll try not to break the examples I've already posted. The interpreter is here:

https://github.com/KSFTmh/KSFTgolf

I'm pretty sure there's something wrong with nested loops in the current version of the interpreter. I'll try to fix it, but for now, some of these might not work.

Length 4

r2eu

This takes a list of numbers as input and prints the sum of the squares of those numbers. Single-digit numerical literals like 2 push their value, e is the exponentiation function, and u pops a list and pushes the sum of its elements.

Length 3

trm

This prints all of the primes up to 1000. t pushes 1000, and r is like a for loop.

Length 2

on

This takes a character as input* and prints the ASCII value of it in binary. o calls Python's ord() function on the top element of the stack, and n converts the top element of the stack to binary.

Length 1

m

This takes a number as input and prints 1 if the number is prime and 0 otherwise. Input is pushed onto the stack at the beginning of the program and the entire stack is printed at the end.

*It uses Python 2's input() function, so string inputs have to be in quotes.

Factoid

Objects in KSFTgolf don't have types. They're converted whenever they're used.

Answered by KSFT on November 19, 2021

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

Answered by sksamuel on November 19, 2021

Common Lisp

Lisp (from LISt Processing) is one of the oldest languages still in use today (only FORTRAN is older). It is notable for being the first language where code is data and data is code; called homoiconicity. It was also the first language to have garbage collection. Originally designed by John McCarthy in a 1958 paper as an entirely theoretical language, it became a real language when Steve Russel realized that the eval function could be implemented on a computer. It's most prevalent in Artificial Intelligence, and is instantly recognizable from its preponderance of parentheses. Common Lisp was designed to unify many of the older Lisp dialects into a more standardized form.

I'll be trying for every snippet to be runnable on it's own, though not necessarily do anything of value. Additionally, because I'm using Common Lisp, the fundamental concepts and a lot of the syntax apply in other dialects, but certain functions won't work in, say, Scheme.

Length 1

*

Because of the emphasis on the use of S-Expressions and lists for coding, there're very few valid expressions in Lisp that don't contain parentheses, called atoms. Anything typed directly into the REPL (read-eval-print loop) is treated as a variable and evaluated as such. * holds the previous value that was printed by the REPL.

Length 2

()

This is the empty list, one of the most important symbols in Lisp. Every proper list in Lisp is terminated with an empty list, similar to how every proper string in C ends with .

Length 3

(*)

This is a basic function call, which consists of a symbol wrapped in parentheses. Lisp doesn't contain operators, they're just functions too. I picked multiplication specifically because it's not actually a binary function; the multiplication operator in Lisp takes an indefinite number of arguments. If it is given no arguments it returns 1, the identity operator for multiplication.

Length 4

`(1)

This is a cons cell, which is just another way of saying it's a pair of elements. In Lisp, each list consists of cons cells connected to cons cells, where the first element (the car) is the value and the second element (the cdr) points to the next cons cell. This forms the basis of Lisp being based upon linked lists. This particular cons cell has 1 as the car and the empty list as its cdr.

Length 7

(not t)

I want to touch on truth values in Lisp. This would return nil. In Common Lisp, t is the symbol for true while nil and () represent false and are equal to each other, but note that this definition isn't standard for all Lisp dialects; Scheme, for example, distinguishes between #f for false and '() for the empty list.

Length 9

(cdr ())

As I said before, the cdr is the tail element of a list, which you can get with the function cdr. Likewise, you can get the head element, the car, with the function car. Pretty simple, right? The car and cdr of the empty list are both nil.

Length 10

(cons 1 2)

Finally, enough length to start working with lists. cons creates a cons cell with the first parameter as the car and the second as the cdr. But instead of printing out (1 2), it gives (1 . 2). Going back to the length 2 snippet, a proper list is supposed to end with the empty list, so the cdr of the last cons cell should point to the empty list. In this case, the last cons cell points to 2, so Lisp informs us that we have an improper list, but still allows us to do it, like how you can make a C-string without a .

Length 11

(cons 1 ())

Now we have created our first properly formed list. It's a single cons cell with a car of 1 and a cdr of (). You'll notice that for every other list, I lead it with a backquote/tick; any other proper list would attempt to evaluate its first argument as a function with the remaining elements as parameters. Strictly speaking, () isn't a list though; it's a symbol composed of a ( and a ) that represents the empty list. Lisp allows you to use almost any printable character in a symbol name and will let you redefine any symbol as you want to.

Length 12

(cdr `(1 2))

This would output (2), not 2 as some people would guess. Remember, each cdr is supposed to point to either another cons cell or the empty list; obviously 2 isn't the empty list, so it must be another cons cell the a car of 2 and a cdr of ().

Length 13

'#1=(1 . #1#)

This would produce a circular list with just the single value 1. If printed, it would print “(1 1 1 1 ...” forever, so that in practice it can be considered an infinite list (on which you can do cdr infinite times to obtain always the same result, itself!). Unless one assigns T to the global variable *print-circle*, in which case it will be printed as #1=(1 . #1#).

Answered by Candles on November 19, 2021

PHP

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1994, the reference implementation of PHP (powered by the Zend Engine) is now produced by The PHP Group. While PHP originally stood for Personal Home Page, it now stands for PHP: Hypertext Preprocessor, which is a recursive backronym.

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

Length 16

The function

http_build_query

builds a query string for an URI from an associative array.
One of many functions that´s closely connected to web development.

Length 15

array_intersect

This function returns the common elements of two or more arrays.

Array function names in PHP are bulky. Apart from implode and explode (respectively join and split), they are almost always prefixed.

Length 14

imagefilledarc

Since version 4.0.6, php has builtin image processing with some pretty sophisticated functions. imagefilledarc is one of them. It can be used e.g. for painting a three dimensional pie chart.

Length 13

if($a >= $b):

This is the alternative syntax for control structures, which ends when it finds a endif; statement. This syntax can be used with if, while, for, foreach, and switch, and end with endif; endwhile; endfor; endforeach; or endswitch; respectively. This alternative syntax is most used to output html without echoing html tags:

<?php foreach($items as $item): ?>
<p><?php echo $item; ?></p>
<?php endforeach; ?>

Length 12

function(){}

This is an example of anonymous function, that can be assigned to a variable, or passed as parameter, for example:

$cmp = function($a,$b) {
  if($a<$b) return -1;
  if($a>$b) return 1;
  return 0;
};
$arr = array(3,1,2);
usort($arr,$cmp);
print_r($arr); // array( [0] => 1, [1] => 2, [2] => 3 )

Length 11

['a'=>[12]]

This statement is equal to array('a'=>array(12)), this short array syntax available since PHP 5.4.

Length 10

$a=array()

This is an example on how to create an array, don't forget to add ; at the end of the statement. The array will have empty length, you can check it using sizeof function. To append at the end of that array, you might use []= operator, for example: $a[] = 12, this would append a number 12 to that array, that similar as typing array(12) at initialization.

Length 9

phpinfo()

This function will print all information about current configuration and variables on your system.

Length 8

__FILE__

Magic constant __FILE__ is a constant that have different value depends on the file its being declared, there are also __LINE__ that shows the line number where its being declared, and __FUNCTION__ for function, __DIR__ for directories (since PHP 5.3). You could see the full list here. They could be used as better way to implement includes, for example: include dirname(__FILE__).'/file.php'; or include __DIR__.'/file.php';, credits: @ismael-miguel

Length 7

4**3**2

Exponentiation operator ** is supported since PHP 5.6, the result of that execution is 262144 (from 4**9)

Length 6

$_POST

This is a global variable that holds value from HTTP protocol with method POST, for example, if you have this form: <form method='post'><input type='submit' name='a' value='b' /></form>', when that button clicked, the current PHP script could access the submitted value using $_POST['a'] that would equal to 'b' string.

Length 5

<?=5?>

This is an example to write number 5 to output, this statement equal to <?php echo 5; ?>, don't forget to enable short_open_tag in your php.ini to enable this feature.

Length 4

NULL

NULL is a constant that holds the value of any variable that hasn't been set yet, or have been unset, or any variable/constant that has been assigned as NULL.

Length 3

1.2

This is example on how to create a float type value. Do not compare float values with equality == operator since they are imprecise. To check whether a variable is a float type, use is_float function.

Length 2

''

This is how you create an empty string in PHP, there are other way such as double quote "". For performance reason, always use single quote unless there are interpolation.

Length 1

a

Anything that written outside <? or <?php and ?> are treated as output, so, if a .php file containing only a character a, that character itself would be the output.

Factoid

Some of the biggest online sites, such as Facebook, Wikipedia, and Yahoo! are powered by PHP.

Answered by Kokizzu on November 19, 2021

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.

Answered by Kokizzu on November 19, 2021

Go

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

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

Length 14

var x [9]int32

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

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

Length 13

var x []int32

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

Length 12

var x *int32

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

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

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

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

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

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

Length 11

interface{}

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

type Stringer interface {
  String() string
}

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

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

Length 10

func X(){}

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

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

Or alternative syntax:

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

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

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

Length 9

package X

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

Length 8

[]int{3}

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

Length 7

strconv

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

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

Length 6

struct

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

type Person struct {
  Name string
  Age  int
}

Length 5

[]int

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

Length 4

x:=3

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

Length 3

1.2

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

Length 2

``

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

Length 1

1

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

Factoid

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

Answered by Kokizzu on November 19, 2021

Ruby

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

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

Length 19 (by a guest)

[1, 2].each{|i|p i}

Ruby supports for loops, but the .each method is preferred. The code in brackets is a block, essentially a single-use anonymous function. Blocks can take parameters, which are enclosed in pipe characters. The p is a shortcut for puts [something].inspect. The .inspect method is a variation of .to_s which provides more details about the object.

Length 18

%i[I love you too]

This is an example on how to create an array of symbols, the result would be: [:I, :love, :you, :too]

Length 17

'1.34'[/(.d+)/]

This is an example on creating snippet then parse it using regular expression. This regular expression means get any dot . that followed by one or more (+) digit (d) then capture it. The result of this snippet is a new string containing .34.

Length 16

'abcdefg'[3..-1]

This statement means, create a string containing abcdefg, then get the fourth (4th = 3) character until the end (last = -1). Another example: [3..3] get the fourth character only (d), [3..5] get the fourth until sixth characters (def), [-3..-1] get the third last character until the last character (efg).

Length 15

%w{i love you!}

This is a shortcut to create array of words (string), that is equal to ['i', 'love', 'you!']

Length 14

[1,2,3,4]*'ab'

Array multiplication with a string equals to call a .join method, the result of this snippet is 1ab2ab3ab4, that also equal to calling: [1,2,3,4].join 'ab'

Length 13

y=->x{x**3}

This is an example on how to create a lambda (or sometimes called anonymous function) using stab operator ->. This statement means create an anonymous function that accept one parameter x that returns x*x*x, then assign this function to a variable named y. Any lambda can be called using .call method, for example:

y = ->(x){x**3}
y.call 8 # 512

This is equal to:

y = lambda {|x| x**3}

Length 12 (by Devon Parsons)

puts "#{$$}"

This snippet shows a couple things. As shown below, puts writes to STDOUT. Code encapsulated in #{ code_here } is evaluated when the string is created, provided the string is made with double quotes. And ruby stores a bunch of useful global variables in double-character shorthand: For example, $~ is the most recent regex match, and in this snippet, $$ is the current process ID. So this snippet writes the current process' ID to STDOUT.

Coincidentally, the ID is of type Fixnum. The string interpolation automatically calls the to_s method on the evaluated code, and to_s by convention returns a string interpretation of the object.

Length 11

x={a:1,b:2}

The statement above is one (of many way to create a Hash or commonly called associative array), to access the value, you can type x[:a], where :a is a symbol (explained in Length 2). To set a value you can type x[:key_name] = 'yayy'. The key of a Hash could be anything not just symbol. Another popular way to create a Hash is using => symbol, for example:

x = { 'a' => 123, 456 => [7,8,9], c: 'wow' }
# x['a'] == 123
# x[456] == [7,8,9]
# x[:c] == 'wow'

Length 10

[*(8..11)]

In this snippet, that statement has the same effect as typing: [8,9,10,11]. The 8..11 part is called Range object. The * operator is the splat operator, in this part, the operator has the same effect as .to_a to array conversion (8..11).to_a.

Length 9

def x;end

This is an example on how to create a function, that example is the same as:

def x
end

To fill the function content, you may type it before the end keyword, for example:

def x
  puts 'the x function has been called'
  123
end

Anything that typed before end keyword would be returned, so in this statement y = x, the y variable would contain 123.

Length 8

9.to_s(2)

This is an example on how to perform base conversion from base-10 integer to binary number, the result would be 1001. You can change number 2 into another base, and .to_i can have parameters too, to parse from string to number, for example '1101'.to_i(2) that would return 13.

Length 7

__END__

__END__ is a line keyword that denotes the end of regular source code, the lines below that line wont be executed and would be gathered in DATA string constant.

Length 6

rescue

The rescue keyword is Ruby's keyword to catch raised exception, we could use this as one-line, for example: x = 1/0 rescue 2, that would set x into 2, or we could use it within begin and end keyword, for example:

begin
  1/0
rescue ZeroDivisionError
  puts 'zero division detected
end

You can find more information about ZeroDivisionError here.

Length 5

BEGIN

BEGIN is a keyword that will execute following code-block before anything else withint the script, for example puts 'b'; BEGIN { puts 'a' } would give an output: a then b. There are also END keyword that executes next code-block before program termination.

Length 4

puts

This function would print a newline on the console, if you add anything as parameter for example: puts('A') or puts 'A', this would print an A character then a newline.

Length 3

'A'

Single quote is one way to create a string, there are another way such as double quote, always use single quote for better performance when no interpolation needed. To get the code-point value of a single string, use .ord method.

Length 2

:x

This is an example on how to create a symbol. Symbol starts with colon followed by quoted string, underscore or alphabet. Symbol is an object to hold immutable string, that normally used as hash's key. To convert it to string, use .to_s method.

Length 1

1

This is an example on how you make a Fixnum object, fixed number is an integer. everything is an object in Ruby, they could have methods such as: 1.to_f would return 1.0 a Float object, or 1.to_s would return "1" a String object.

Factoid

Gems is Ruby's package (library and programs) manager.

Answered by Kokizzu on November 19, 2021

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.

Answered by curiousdannii on November 19, 2021

Scala

Scala is a JVM-based, statically-typed (mostly), hybrid functional/object-oriented language, with type inference, higher kinded types, and generics.

Factoid: Scala started with the man behind Java generics and a lot of the Java compiler, Martin Odersky.

1

Snippet

;

Explanation

There isn't much need for semicolons in Scala (unlike its cousin, Java), but they can still be found in some places, such as for statements (also known as "for comprehensions"). For example:

for (i <- 0 to 10;
     a <- 0 to 10
) yield (i, a)

Will return a list going something like (0, 0), (0, 1)... (1, 9), (2, 0)... (10, 10).

2

Snippet

()

Explanation

Scala's Unit type has only one value: (). Used like Java or C's void. Don't be fooled, though: it's not an empty tuple! This type is mostly returned from functions with side effects, to distinguish them from the purely functional ones. In Scala, every function must return a value. If they don't, they implicitly return ().

3

Snippet

???

Explanation

An operator which just throws NotImplementedError. Luckily, thanks to Scala's powerful type system, it can be put in any unimplemented function and still be typesafe:

def notImplemented: Int = ???
def foo: String = ???

One of the best parts of Scala is that there's very little baked-in as compiler magic, and you can write most of the builtins yourself. Operators are simply functions with names that contain symbols - ??? itself can be defined as:

def ???: Nothing = throw new NotImplementedError("an implementation is missing");

4

Snippet

None

Explanation

While Scala does have null as part of the language (as an unfortunate holdover from Java), it also has a pre-made option type, called Option[T]. If an optional value isn't there, its value is None. If a value is optional, make it an Option, and you won't ever have a NullPointerException. You can also implement Option yourself, like so:

sealed trait Option[+T]
case class Some[T](value: T) extends Option[T]
case object None extends Option[Nothing]

5

Snippet

(1,2)

Explanation

A 2-tuple (a pair) of integers, 1 and 2. Especially useful for returning multiple values from functions, as well as pattern matching. Observe:

def printPoint(p: (Int, Int)) = p match {
    case (x, y) => println("X coordinate: " + x + ", Y coordinate: " + y)
}
printPoint((1,2))
// prints "X coordinate: 1, Y coordinate: 2"

6

Snippet

()=>()

Explanation

An anonymous function. As a functional language, Scala has first-class language support for anonymous functions. To dissect this snippet, it's a function which:

() - Takes no parameters,

=> - And returns...

() - Unit!

7

Snippet

s""""""

Explanation

The empty string... with a twist. If you begin and end a string with triple-quotes, you can include unescaped characters inside. For example:

"""

"""

Is equivalent to:

"n"

Also, a string beginning with s can have interpolated values in it. For example:

val num = 10    
val str = s"There are $num nums"
// str == "There are 10 nums"

It gets better though: with braces, you can put expressions inside!

val str = s"2 + 2 == ${2 + 2}."
// str == "2 + 2 == 4."

8

Snippet

Future{}

Explanation

Futures are things that will happen or be computed... sometime later. Scala has a lot of different models of concurrency that are each useful in their own way (like the Akka framework), and Futures are one of them. Future{} computes (). Pretty useless, but if I have something really expensive to do, like compute 2 + 2 and multiply that by 5, they're pretty handy:

Future {2 + 2} map {_ * 5)

They're also great for I/O. Admittedly, you have to do a couple of imports for this, but they're in the standard library.

10

Snippet

type N=Int

Explanation

This is a type variable called N, which refers to the type Int. You could now write:

val num: N = 1

And it would work.

Addendum: I said type "variable", but these can't vary during runtime. You can use these for some nifty type-level programming like the Heterogeneous List, or HList, which is a List that contain several different types of elements while still being typesafe. If you're interested, watch Daniel Spiewak's "High Wizardry in the Land of Scala": http://vimeo.com/28793245.

16

Snippet

implicit val a=1 

Explanation

Have you ever used a heavyweight dependency injection framework like Guice or Spring? If so, you know that dependency injection is (in essence) supplying objects with their dependencies at construction, so that they can stay loosely coupled. The issue with doing this the easy way is that constructor signatures quickly grow out of control when you start to build large dependency graphs. To fix that, you bring in a DI framework, and soon after, your project has 50k lines of XML. :-(

Now for a seemingly unrelated question: have you ever needed to call a series of functions, all sharing a few parameters? Has that ever become so cluttered that you added an extra class, just to put the parameters in one place?

Implicits give you a way to inject a value of a particular type in a particular scope into a function call. This way, functions can ask for a value without you needing to explicitly provide it. It's filled in automatically! One of the best parts, and the reason this relates to DI, is that constructors also work with implicits. You can create huge parameter lists in your constructors to keep them loosely coupled, but users of your classes will never have to supply all of the parameters manually (but they can, if they want).

This particular snippet creates an implicit value of type Int in the current scope, with the value of 1. If any function calls require an implicit Int, they'll automatically be fed 1.

17

Snippet

({type I[T]=T})#I

Explanation

This is a type lambda (in this case acting like an identity function for types). It's a combination of a type member (mentioned above) (type I[T] declares a type constructor I taking a type parameter T ), a structural type (everything between the braces denotes a type), and a type projection (#I accesses the member I of the structural type in braces).

In Scala 3, this can be expressed much more nicely as [T] =>> T.

18

Snippet

list.reduce(_ ^ _)

Explanation

Underscores have various uses in Scala. Here, we can use them to define a trivial function more concisely. The _ ^ _ is really shorthand for (a, b) => a ^ b.

The snippet reduces a list of what may be integers by XOR-ing them. reduce is just one of the many useful methods in the standard library. There are many others, such as map, heads, distinct, groupBy.

Answered by Schalat on November 19, 2021

GNU Make

I'll go out on a limb on this one. I think this may well be the first time that make has been featured in PPCG.

Factoid

Make may be considered to be a functional language.

Length 0 snippet

I don't think length 0 snippets are required, but here is one anyway. I think this might be the most useful of all length 0 programs. With an empty Makefile (or even no makefile at all), make still has a bunch of built-in rules. E.g. there are default built-in rules to compile a .c file into a .o or binary, given the .c file exists in the current directory. So if we do:

make hello.o

make will find the .c to .o rule and compile hello.c to give hello.o

Similarly if we do:

make goodbye

If there is a goodbye.c file in the current directory it will be compiled into the goodbye binary.

Length 1 Snippet

TAB

Yes, the TAB character. While this doesn't do much on its own, it has great significance in Make. Specifically all recipe lines following a target definition in a rule MUST start with a TAB. This causes all sorts of frustrations when debugging makefiles when TABs and spaces get mixed up.

Length 2 Snippet

$@

This is an automatic variable for use in recipes. It will expand to the filename of the target of the rule. There are other useful automatic variables.

Length 3 Snippet

a:=

Shortest simply expanded variable assignment. The variable a is set to "" immediately when the Makefile is first parsed. If instead we do a=, then the assignment is recursively expanded, i.e. expansion is deferred until the time the variable is actually referenced.

Length 4 Snippet

W:;w

Shortest marginally useful complete rule specification. This defines a target W with a rule that simply runs the w shell command. Thus

make W

is equivalent to:

w

This is an alternative rule syntax in that the recipe follows the target on the same line separated by a new line. More commonly the recipe lines immediately follow a separate target line, with TAB characters starting each recipe line.

Length 5 Snippet

$(@D)

Another automatic variable. Similar to $@, but this expands to the directory portion of path, with the filename and trailing / removed.

Answered by Digital Trauma on November 19, 2021

F#

F# is a strongly typed, multi-paradigm programming language that encompasses functional, imperative, and object-oriented programming techniques.

All the snippets included here can be run online at: http://www.tryfsharp.org/Learn (exception: FSI snippet).

Length 9 Snippet

(10, "Z")

Tuples! a Tuple is defined as a comma separated collection of values. While Lists (and Arrays) gravitate towards the concept of a Set, Tuples are more like a data structure that groups related values.

The snippet defines a 2-tuple. One value is integer, the other string. F# annotates the type as: int * string

Tuples are considered ad hoc types, so they are passed as a single argument, can be a return type and so on.

F# has two built in functions to help with tuples: fst and snd that return the first or second element of a Tuple respectively. Tuples are not limited to just two elements, though.

Length 8 Snippet

[-9..10]

F# allows to define ranges of sequential values. This snippet generates a list of 20 integer elements, -9 and 10 inclusive.

You can define stepping values, for example [0..10..50] will yield a list of 6 elements: [0; 10; 20; 30; 40; 50].

The range syntax is the same for lists and arrays.

Length 7 Snippet

let a=1

We can now define values. Values in F# are immutable by default, that is the reason we avoid the use of the term "variable".

The snippet defines an immutable value "a" that contains a 1 (integer).

Length 6 Snippet

2.**8.

Now we can use the Power function.

Note that I could not call the Power function before with arguments "2" and "8", because [the arguments] would be considered integers. The decimal points make the compiler to infer a floating point number. This snippet correctly returns a 256.0 (float) value.

Floats in F# are double precision.

Length 5 Snippet

[|0|]

At five characters, we can define an array with one element (as mentioned before, the compiler infers the type to int[]).

Not to be confused with a list. An empty list is defined simply by the square brackets like this: []

The element separator, in both lists and arrays, is the semicolon (;) as in [| 1;2;3 |]

Length 4 Snippet

(**)

It's not an emoticon, it is a multi-line comment in F#. For some odd reason I didn't find this syntax intuitive. I got used to it until much later.

Single-line comments are double-slash (//), just like C++, C#, Java, etc.

Length 3 Snippet

nan

Three characters unlocks many basic arithmetic operations (1+2, 9*9 and so on). But I picked nan. It is a shortcut function that simply returns System.Double.NaN.

Useful to compare (or match) the result of a function.

Length 2 Snippet

;;

I could've used an empty string ("") as the snippet. That would create a function that returns an empty string, but it is the same concept as the length 1 snippet.

Instead, I picked the empty statement in F# Interactive (FSI). FSI is a REPL tool that allows you to declare, construct and otherwise experiment with your code in an interactive manner and it is very useful. In my opinion, the ;; is used more frequently than empty strings.

You must append double semicolons (;;) at the end of your statements in FSI to indicate the end of input.

Length 1 Snippet

0

A function that returns zero (the compiler infers the type to integer). Commonly used as the final statement to return the program exit code.

Factoid: F# uses type inference. The programmer does not need to declare types - the compiler deduces types during compilation.

Answered by Mike Rod on November 19, 2021

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.

Answered by Charles on November 19, 2021

T-SQL

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

Answered by bmarks on November 19, 2021

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.

Answered by Johannes Kuhn on November 19, 2021

GNU Sed

I am self-imposing a more restrictive requirement - all snippets will be complete sed programs.

Factoid

sed is a turing-complete language. Here is a proof.

Length 0 Snippet

I don't think a length 0 snippet is strictly required, but since it actually does something in sed, here it is:

Sed is the "Stream EDitor", i.e. it reads the stream (line-by-line) from STDIN, edits, then outputs to STDOUT. The zero-length sed program simply copies STDIN to STDOUT. Thus the cat utility may be emulated by sed. The following are equivalent:

cat a.txt b.txt > c.txt

and

sed '' a.txt b.txt > c.txt

Length 1 Snippet

=

This sed program prints the line number of each line to STDOUT. This is approximately equivalent to:

nl

or

cat -n

although the sed version puts the line number on its own line.

Length 2 Snippet

5q

Copies STDIN to STOUT and quits after line 5. This is equivalent to:

head -n5

You might be starting to see a bit of a pattern here - sed can be used to emulate many of the standard core-utils tools.

Length 3 Snippet

iHi

inserts "Hin" before every line. Meh.

Length 4 Snippet

/a/d

A lot of sed's power is in its regex capability. This program causes all lines matching the regex a to be deleted from the stream. All other lines will still be output to STDOUT. This is equivalent to:

grep -v "a"

Length 5 Snippet

:l;bl

This is an infinite loop. We all love CPU-hogging infinite loops. Defines a label l, then branches (jumps) to it. Ad infinitum.

Length 7 Snippet

s/a/A/g

By default, sed applies s commands such that it will match just the first occurrence on each line. If you need it to match (and substitute) every occurrence on a line, then the g flag at the end of the s command will do this.

Length 8 Snippet

y/01/10/

The little used y command is similar to the tr shell utility (though not quite as flexible). This program will switch all 0s with 1s and vice versa.

Length 9 Snippet

1!G;$p;h

This snippet is actually 8 bytes, but requires the -n parameter to sed to suppress default output, so as per standard code-golf rules, I'm counting this as 9. This program reverses the lines in the stream. So:

sed -n '1!G;$p;h'

is exactly equivalent to:

tac

Length 10 Snippet

s/[ <TAB>]+$//

This is a revisit of the (incorrect) length 6 snippet. This strips trailing whitespace (spaces and TABs) from lines.

Answered by Digital Trauma on November 19, 2021

Powershell

Factoid:

As part of Microsoft's "Common Engineering Criteria" Powershell is designed to provide an automation platform and unify the management experience across all MS Server products. It leverages both the command line strength of a robust shell and the object awareness of the .NET infrastructure.

To handle a highly complex environments the standard naming convention for Powershell commands and functions follow a Verb-Noun structure (ex. Get-Help). This means that in favor of clarity and readability long names are actually encouraged. However because this is a "working admin's shell" there are 2 tools that keep this from being a burden. The first is "tab completion" for commands, parameters, filenames, etc. The second is a robust alias structure, many of these examples will feature aliases.

Length 1

|

Pipe Piping is a common feature in Shells. Powershell improves on this by piping objects instead of strings. So if (for example) a command selecting a file is on the left side of the pipe, then all of the complex attributes {Full path, directory, CreationTime, etc.} of that file are available on the right side of the pipe.

Length 2

gm

gm is an alias for Get-Member which presents the various properties and methods that are available for an object. The most common of usage will be following a pipe. Using gm on a file reveals 24 methods and 21 properties native to the System.IO.FileInfo object type. gm is one of "the 3 things that reveal everything in Powershell" if you know only these 3 things you can use them to discover every function available.

Length 3

gci

gci alias for Get-ChildItem (other aliases are dir and ls). In it's simplest sense gci retrieves the contents of a directory; you can apply filters, selectively recurse, and do everything that the DOS and Bash equivalents can. The real power though is that Get-ChildItem has the ability to navigate "Powershell Providers." Providers exist for Environment Variables, the Registry, Certificates, and VM datastores; meaning that once you connect to the provider you can browse and interact with these abstract environments using familiar command-line navigation and logic.

Length 4

help

help alias for Get-Help, and the second of "the three things that reveal everything". Help reveals structure, syntax, and function. For "professional" cmdlets and modules examples will be included. However help is dynamically aware of what's going on, so even for the most slapped together amateur functions you can use get-help to see the basic parameters and syntax.

Length 5

h |fl

This is the first example that is not just a component but is actually full, complete, and practical in daily usage without any further parameters or modifications.

h alias for Get-History. Session History automatically logs your commands, and you can bring up recent commands with the up arrow. However to get a complete picture of command history use Get-History to present this array of information.

| pipe, in this case we are piping an array of HistoryInfo objects. (note: space before or after a pipe is optional... but it sure makes examples more readable. So this could also be a length 4 example. Working from the command line I tend to insert a space before as an old habit.)

fl is an alias for Format-List. Commands beginning with Format- are display options, no data is manipulated. Format-List accepts the piped input and displays the properties (for each array item) as a separate line. This helps to quickly expose statistics like ExecutionStatus, StartExecutionTime, and EndExecutionTime for each history item.

Length 6

(h)[0]

This is a very simple demonstration of some complex concepts.

h as we've already covered is an alias for the Get-History Cmdlet. This Cmdlet returns an array of objects.

( ) brackets in an expression like this work like in a math formulas, you process what's inside the brackets to get the result before other operations are performed. So by using (h) or (get-history) we are designating that things outside the brackets will not be interacting with the command itself, but with the resulting array.

[0] this shows a way of directly specifying one element within an array, following standard comp-sci usage 0 represents the "first" element in that array. This example returns element 0 of the array returned by (Get-History). This can be useful when you want to systematically retrieve the Nth element of a sorted array, change the Nth letter of a string, or change the Nth octet of an IP address.

Length 7

-Whatif

-Whatif is a "common parameter" enabling a safety routine within Powershell. Get-Help states: "When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the command, instead of executing the command."

So if you have generated a list of files stored in the variable $deletePending and your next step is to run $deletePending | Remove-item if you want to make sure that a typo isn't going to ruin your week you can run a simulation of that command $deletePending | Remove-item -whatif Each simulated step will output a line similar to:

What if: Performing operation "Remove file" on Target "C:folderfile.tmp".

You can also turn WhatIf on for an entire session if you want to do extensive testing. Most native "danger zone" cmdlets support the WhatIf parameter, and support can be integrated into your custom functions.

Length 8

if(h){h}

This demonstrates the logical flow "IF the statement inside the brackets resolves to a Binary True, then run the statement in the curly brackets." It's important to understand that a Binary True ($true) can be achieved in multiple ways. Some examples:

if ($True)        if (1 -eq 1)        if (Get-Date)       if ("False")

That last one surprises people sometimes; but it's strong logic, "False" is a valid string and no valid string will ever equal Boolean False ($false).

In the 8 Length demo, the test being evaluated is "does (Get-History) return $False?"

if ( h ) { h } will return $false if you run it in a brand new session, run it a second time and it will return $true because now a history item exists. Being able to evaluate using cmdlets and functions can be very powerful, as long as you understand if and when a $false can be returned.

Length 9

-computer

This parameter exists for cmdlets that support "implicit remoting" (such as get-process, stop-process, get-service, get-eventlog ). Generally speaking if you could do it through the management GUI or some form of WMI request you can now automate it through Powershell Cmdlets.

Length 10

get-acl c:

If you have a file sharing structure then 1 of 2 things is true; either you need to "clean up the permissions one of these days" OR you've automated your standards.

In both cases get-acl and set-acl are better than the tools you've had before.

This is another tool that leverages powershell providers so it's just as easy to work with the ACL of HKLM:SofwareExampleSoft as it is with C:Program FilesExampleSoft. Build a few scripts around the custom installs in your environment and you'll never grant "Local Admin" to a user again.

Length 11

Get-Content

"Gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns a collection of objects , each of which represents a line of content."

Any good shell better be able to read a file's contents, so why is Get-Content worth mentioning?

-encoding  -raw  -stream  -delimiter  -readcount  -totalcount  -tail

Examining the parameters we see it can do a lot more than just push stdin to stdout. For example we can pull the elusive Zone ID from the alternate data stream to see whether $file is flagged as originating from a trusted or untrusted zone.

Get-content -path $file -Stream Zone.Identifier

Length 12 - modular function component 1

function f{}

Creates a function named f. Code within the curly brackets will be run whenever f is called.

In case you're wondering, since this is an empty function evaluations of f will find it equals $false.

Length 13 - modular function component 2 (updated)

{my original length 13 was actually 12, so I'm re-working this entry}

$MyInvocation

This automatic variable exists for functions and other script blocks. It contains valuable diagnostic information about how a script block was invoked, including arguments and pipeline status.

If we simply place $myinvocation into our function, calls to f will return the invocation properties.

Length 14 - modular function exploration1

$a=1..5+8
f @a

Running this will return the invocation properties from our function, which you can use to verify the breakdown I'm providing here.

This demonstrates populating a variable, and then calling our function with that variable as an argument. Since the ';' represents a break in the pipeline this can also be written as $a=1..5+8;f @a

$a = creates (or overwrites) the variable a

1..5 populates $a with the numbers starting at 1 and ending at 5 (meaning that $a has actually become an array of integers).

+8 looks like math, but since we're working with an array of integers this is really adding the integer 8 to the existing array

f since we defined 'f' as a function earlier we can now call it anywhere within the session just by using its name. Best Practice is to name functions following the Verb-Noun convention. Since function names are automagicly candidates for tab-completion do yourself a favor and only use short function names for silly things like code-golf.

@a Here the space separates the function name from it's arguments.

The @ (array identifier) is interesting. If we call f $a then we pass the array as a single argument. By specifying f @a we pass each individual array element as an argument. The function will behave as if called like this f 1 2 3 4 5 8

Length 15 - modular function component 3

$args| %{$_+$_}

If you ran the "Length 14" exploration code you'll see the "UnboundArguments" invocation property, the $args automatic variable contains an array of arguments passed to a function as undeclared parameters.

% is an alias of Foreach-Object, which accepts the piped object and individually submits each element to the following script block { }

$_ contains the current object in the pipeline context.

$_ + $_ since we are in a foreach context our current object is each individual integer in our array, we demonstrate that by adding each Integer to itself. Since the + operator is context aware it reacts appropriately to either integer or array contexts.

Current Module:

Function f{
$myinvocation
$args| %{$_+$_}
}

Answered by H.R.Rambler on November 19, 2021

Rebol

All the examples below work verbatim in Rebol 3. Just type them into the Rebol 3 console (REPL) and see an immediate result. Obviously for example 14, if file.txt isn't present then it will throw an immediate error :)

25

find "foobar & baz" "bar"

This returns - "bar & baz"

find works on a series returning either a series where it matches or none if no match was found.

Some other examples:

find "foobar & baz" "boo"              ; none
find ["foobar" "bar" "baz"] "bar"      ; ["bar" "baz"]

24

random/only words-of lib

This returns a random word from the Rebol lexicon :)

lib is an object containing all the words defined by Rebol and also any created when importing modules. words-of returns a list of all the words within an object. random/only then picks one word at random from this list.

23

f: function [n] [n * 2]

This creates a new function called f which takes one argument and doubles the value received (the last expression evaluated is automatically returned by the function).

There are a few different function generators in Rebol to choose from. For eg:

  • function - all variables created within block are local

  • func - all local variables must be declared with /local refinement

  • does - has no arguments or local variables.

See Functions chapter from the Rebol/Core User Guide for more info.

22

reduce [1 + 2 * 3 red]

The reduce function evaluates multiple expressions and returns a block of results. There are two expressions in the above block so it returns a block with two values: [9 255.0.0]

NB. For the eagled eyed who were expecting 7 from 1 + 2 * 3 this is because Rebol has no operator precedence and simply evaluates operators from left to right. Use parenthesis to enforce precedence, for eg. 1 + (2 * 3) would return 7.

21

compose [blue (blue)]

This returns a block with [blue 0.0.255]

The compose function evaluates any code found in parenthesis (paren! datatype) but leaves everything else untouched.

20

red + blue = magenta

This returns true because Rebol supports tuple arithmetic.

19

type? [email protected]

Use type? to find the value's datatype. This example returns email!

NB. As you can see from the examples so far, Rebol comes with a lot of handy datatypes

18

$0.1 + $0.2 = $0.3

The above returns true because these are money! datatypes. So ideal for high precision arithmetic original link down at moment .

17

<div class="red">

This is a tag! datatype.

16

24:00 - now/time

This returns how long there is left in the day (in HH:MM:SS - a time! datatype).

NB. This code shows the first example of a refinement! in Rebol. With refinements you can modify the functions behaviour including adding extra arguments. By itself now would return the current date and time (date!). The /time refinement causes now to return the time only (time!).

15

{"a" {foo} "c"}

This is one way to represent a string! datatype in Rebol. Another way to express this would look like this "^"a^" {foo} ^"c^"" which isn't as visually appealing!

NB. Using braces over double quotes allows spanning of multiple lines and also nested {}. The ^ is used to escape the quoting delimiter. So {closing brace is ^} opening brace is ^{} would be how an unbalanced {} would look.

14

read %file.txt

This will read in the entire contents of file.txt into memory. Any word prefixed with % is a platform-independent file! datatype.

NB. read can also suck content down from other sources, eg. read http://www.rebol.com (this is a url! datatype).

13

100'000'000.0

This is the same as 100000000.0. Single quotes (') are allowed to split up numbers for readability.

NB. Commas can also be used to mark decimal places, eg. 100'000'000,0 is a valid decimal! datatype.

12

something: 1

This sets the word something to represent the value 1.

NB. Rebol is quite liberal in what can be used for a word as long as it doesn't clash with any known datatype. For e.g. another valid 12 length answer would be a-.+!&'*?: 1

11

12-Dec-2012

This is a date! datatype.

10

to-hex red

Functions in Rebol have fixed arity. The to-hex function expects one argument and returns a hex issue! datatype.

NB. The example given returns #FF0000 which is ideal for CSS colours.

9

#{FF0000}

This is hex (base-16) literal notation. Other bases for this binary! datatype are also available.

8

12:15:33

This is a time! datatype (HH:MM:SS).

7

newline

Gives Rebol's internal (platform-independent) newline character. Written as a character literal, this would be #"^/" -- the line-feed character.

NB. The # prefix here denotes a single character and not a string (ie. a series of characters like "foobar"). And the ^/ is Rebol way of representing the control code for LF.

6

speed?

Returns simplistic (and approximate) speed benchmarks for evaluation, CPU, memory & file IO. Handy for comparing the speed of your Rebol on different machines.

NB. General convention is that postfixing word with ? is used to signify what's / what is its. For eg. length? list or type? word

5

1 = 1

Equality test.

The operator = is infix synonym for equal?. == for strict-equal?.

NB. Spaces are important because 1=1 would be recognised as a word (and an invalid word at that).

4

why?

Explains the last error (that occurred) in more detail. It does this by opening your web-browser on the necessary webpage that documents the error.

For eg. foobar would produce the error ** Script error: foobar has no value. Typing why? next will open browser window pointing at http://www.rebol.com/r3/docs/errors/script-no-value.html

NB. This is the first function call example given. why? is a word which points to a defined function (source why? for details). When Rebol interpreter hits a word like this it invokes the function. If the function requires any arguments then Rebol evaluates the necessary words that follow and passes them to the function.

3

red

This returns a tuple which in this case is a tuple of RGB values (for the colour red!).

NB. And red is not the only colour defined in Rebol - http://rebol2.blogspot.co.uk/2012/03/color-names.html

BTW. Red also happens to be the name for an alternative version of Rebol - http://www.red-lang.org/

2

no

Rebol comes with a few synonyms for true and false... yes no on off

NB. These are all just words in the Rebol lexicon (including true & false) so all can be redefined. So if you peek underneath you'll find the truth is actually #[true] (literally!).

1

;

Everything after a semicolon to end of the line is ignored by the Rebol interpreter.

NB. Space(s) are important to Rebol because it interprets the words it sees. But ; is one of those exceptions where it cuts across this.


Factoid

Rebol is a dynamic programming language designed by Carl Sassenrath with data exchange in mind. NB. Douglas Crockford has cited Rebol for being an influence on JSON design.

It had been proprietary but Rebol 3 was finally opensourced on 12-12-2012 just before the world ended :) (according to the Mayan calendar!)

Answered by draegtun on November 19, 2021

The Infamous Shakespeare Programming Language

Shakespeare Programming Language was created in 2001 by two Swedish students, Karl Hasselström and Jon Åslund, and it combines, as the authors proclaim,

the expressiveness of BASIC with the user-friendliness of assembly language.

Answers go from top to bottom. Also, it's common to see me refer to older or previous snippets.

(link for myself: edit)

Factoid:

Shakespeare's code resembles, as one would expect, a Shakespeare play, where the variables are characters on the play and their value changes as they are "insulted" or praised".

Length 1 snippet:

I

Shakespeare's code is divided in Acts, and the acts are themselves divided in Scenes, for "jump-to" causalities. Defining an Act as Act I means that it will be the first piece of the code to be run, per example - but not only.

Length 2 snippet:

as

Used in a comparative between two "characters".

Length 3 snippet:

day

By now, you may be getting the feeling that SPL is very verbose. And weird. And you've seen nothing yet. day, in SPL, is 1. All "positive" and "neutral" nouns are considered as 1, as well as all "negative" ones are -1.

Length 4 snippet:

rich

What is rich? An adjective. In SPL, adjectives make the value of the noun they're attached to multiply by two. See implementation on snippet 14.

Length 5 snippet:

Act I

Implementation of the first snippet. All acts may be given a title, such as Act I: Hamlet must die!, since everything after the Roman numeral is ignored by the parser.

Length 6 snippet:

better

Every language has conditions, and SPL is no exception. Except, since this is a language with a lengthy syntax (and did I mentioned it to be weird?), its conditional statements are going to be long. Having Ophelia ask Juliet Am I better than you? is like having if (Ophelia > Juliet) on most "normal" languages. And, of course, you can ask the other way around: Am I not better than you? is the equivalent of if (Ophelia < Juliet). And you can already guess how the = is translated to SPL: as good as - usage of code snippet 2.

However, good/better is not the only way to make comparisons in this shakesperian language, you can use any adjective. The same principle of snippet 3 applies here as well, with "positive" adjectives having the value >, while "negative" ones mean <.

Length 7 snippet:

Juliet:

This is the invocation of a variable; after this, his/her instructions/declarations/whatever will follow.

A limitation of SPL is that it has a limited number of variables: Romeo, Juliet, Hamlet, Ophelia, MacBeth and so on are a few examples of "characters" that will appear on a Shakesperian program.

Length 8 snippet:

[Exeunt]

[Exeunt] is placed when all "characters" leave the "stage". Hopefully I can elaborate a bit more later on about the interaction between characters. Generally is the last instruction of any SPL program, although [Exeunt] isn't specifically the terminal "character" of the language. For another example, see snippet 27.

Length 9 snippet:

as bad as

Nine characters just to represent a mere = - using snippet 2. Have I mentioned that SPL is weird? See snippet 30 for examples. (and yes, there's more than one way to output it)

Length 10 snippet:

difference

A fancy way of representing -, a subtraction. You can have math operations on SPL, even though you'll probably need a full day to get it right.

Factoid (since I managed somehow to reach ten snippets of code, let's take a bit of a break and have another factoid about SPL)

If you want to run your shakesperian code in all its glory, there's this site - I'm still testing it, since I discovered it not even five minutes ago. There's also a way to translate it to C using a translator.

Another site for running SPL code is this one that works by internally translating the SPL code to another esoteric language: Oracle PL/SQL.

Length 11 snippet:

[Exit Romeo]

Yes! At last I can talk about the interaction between characters! In order to have its value changed or to interact with others, a "character" must be on stage - entering with [Enter Romeo]. If a character is addressed to but is not present, there's a runtime error and the program stops. Because, in SPL, the value of the variables is set by the amount of names they're praised with - or insulted with - by the other characters on stage. I feel that I should put an example to clear some confusion my lame explanation may create, but perhaps it's best to delay that a few snippets.

Length 12 snippet:

Remember me.

SPL is pretty "basic", alright - but it has stacks! When, per instance, Romeo tells Juliet to "remember him", he's actually telling his loved one to push the Romeo's value into her stack. Popping the value is done with Recall your happy childhood!, or Recall your love for me, or basically any sentence that begins with Recall - the rest is just artistic drivel, like snippet 22.

Length 13 snippet

Let us return

The Shakesperian way of having a goto. And this is where the Acts and Scenes come in handy. If Romeo tells Juliet we shall return to Act II (yes, again, there are multiple ways of write it), the program will jump to that specific part of the code. It's also seen alongside conditional statements.

Length 14 snippet

my little pony

Yes, it was a series back in the 80s. Here, it's 2*1. Why? Because a pony is a (somewhat) positive noun and little is an adjective. So, remembering snippets 3 and 4, we have little = "2 *" and pony = "1".

Length 15 snippet

Speak thy mind!

In a SPL program, you'll see this (or Speak your mind!, which is the same) a lot. This basically outputs the value of each "character" in digit, letter or anything else, depending on the character set being used by your computer. There's also Open your mind. that does almost the same thing, albeit only outputting in numeric form.

Length 16 snippet

You are nothing!

When someone tells you this in real life, you'll feel depressed. When Ophelia tells this to Hamlet in Shakespearian programming, Hamlet feels worthless. What does this mean? That Hamlet = 0.

Length 17 snippet

Ophelia, a wench.

In a screenplay, before the actual play starts, the characters must be presented. In most programming languages, the variables must also be declared before use. Seeing that SPL is a programming language that resembles a screenplay, this is how you declare its variables, by stating which are the ones appearing during the program.

But what does "a wench" mean? Does it mean that it's a specific (and cool) data type name? Well... I hate to disappoint you, but it means nothing: everything after the comma is disregarded by the parser, meaning you can put there the most outrageous drivel you can think of.

Length 18 snippet

lying sorry coward

-4 for all earthly creatures. Why? Because 2*2*(-1) = -4.

Length 19 snippet

Romeo:
 Remember me.

At last!!! I can finally output a full correct syntax instruction (albeit a short one)! This is how you use snippet 12: firstly you declare who's talking, then on the next line you write the "dialogue". Normally, only two "characters" are on stage, to avoid making the parser sad and confused. When you need another "character", you take one from the stage and replace him by the new one.

Length 20 snippet

cube of thy codpiece

I wanted to elaborate a bit more for this one, but, truth be told, the things I come up with are still too short for this snippet length. And, so, I bring you this, which ends up being -1 - because (-1)3 = -1 (and codpiece is a "negative" noun, since they're uncomfortable and all). SPL understands a few more elaborate arithmetic operations as some exponentiation and square roots.

Factoid (yet another one, since we've reached another milestone)

The "Hello World Program" in Shakesperian has 89 lines and more than 2400 characters long, as seen here.

Length 21 snippet

Listen to your heart.

In snippet 15 you outputted something; here, you input a number to the program. If you want to input a character, you'll use Open your mind. instead. And, needless to say, this value will be stored in the "character" being spoken to.

Length 22 snippet

Recall your childhood!

Popping an integer from a stack is done with this, as explained on snippet 12. When, per instance, Ophelia tells Hamlet the aforementioned sentence, it causes Hamlet to take an integer from his stack and assume that value.

Of course that, as long as the word recall is starting the sentence, you can fill in the rest with pretty much anything your creative shakesperian mind desires.

Length 23 snippet

Are you better than me?

Implementation of snippet 6. When a "character" makes a question like this to another, what he/she is doing is equivalent to if (x > y) on more common programming languages. The follow-up of this instruction must be delayed until I have more characters available.

Length 24 snippet

[Enter Romeo and Juliet]

Yes, "characters" may enter in pairs. It's not required to have one "character" entering the stage, being followed by another.

Length 25 snippet

remainder of the quotient

25 characters just to write a %. 25 characters to have the remainder of a division. And to use it? Well, that's even bigger - see snippet 75.

Length 26 snippet

Let us return to scene II.

Here it is, a goto in SPL, which works as one would expect in a programming language. A thing is: you can jump between scenes in the same act, and between acts; but you cannot jump between scenes in different acts.

Length 27 snippet

[Exeunt Ophelia and Hamlet]

When more than one "character" leave the stage, instead of Exit, and keeping in tradition with SPL's theatrical nature, the latin word "Exeunt" is used. Sometimes it can be replaced just by snippet 8.

Length 28 snippet

Scene I: Ophelia's flattery.

Declaring a Scene. As you can already expect if you've been coping with me, the important bit is the Scene I, the rest is artistic fluff.

There have been some compilers made (like this one that compiles from SPL to C, written in Python) that instead refer to the text after the numbering of the Act/Scene. While more logical (after all, during a play, having the characters saying lines such as "let us return to Act I" may be deemed silly), I'm sticking to the original way.

Length 29 snippet

You pretty little warm thing!

Yes, yet another constant (since we need way more characters to have arithmetic operations). This one is equal to 8, because 2*2*2*1 = 8.

Length 30 snippet

You are as cowardly as Hamlet!

Saying this to, per instance, Romeo, means that Romeo = Hamlet. Like snippet 9.

Factoid (yes, another landmark reached!)

This language was created for an assignment in a Syntax Analysis course - thus, no SPL compiler was created by the authors. More: it seems SPL's authors have severed their ties with their creation, since nothing appears to have been modified in the language since 2001...

Length 31 snippet

Am I as horrid as a flirt-gill?

Yes, I know, it's somewhat repeating snippet 23, although, here, we're comparing the "character" who speaks with a "flirt-gill" (of, if you prefer, if (Ophelia == -1)). The thing is...

Length 32 snippet

If so, let us return to scene I.

... now I can introduce the then of SPL, and the conditional jump-to, and the Shakesperian way of implementing loops. You can, per instance, make Romeo assume the value 0, increment his value while doing some other task and stop when he reaches 10, proceeding with the program afterwards.

Length 33 snippet

If not, let us return to scene I.

Just a reminder that, instead, we can instead proceed forward to another scene if the condition we tested for is false.

Length 34 snippet

Open your mind! Remember yourself.

Two instructions in a row, yippie! The first one reads a character, the second one pushes it into the other character's memory stack.

Length 35 snippet

Act I: Death!

Scene I: Oh, shit.

The proper way of declaring an Act and a Scene. Add artistic mush tastefully.

Length 36 snippet

Thou art as sweet as a summer's day!

Another way of saying that the "character" being spoken to will receive the value 1 - because summer's days are nice and pleasant.

Length 37 snippet

Art thou more cunning than the Ghost?

Ophelia asking this question to Hamlet means, translating this to a less readable programming language, if (Hamlet > the Ghost). It's snippet 23 all over again, yeah - but it goes to show you that it's not required to ask the "characters" if they are better than each other: any other question will work too.

Length 38 snippet

[Enter the Ghost, Romeo and the Ghost]

Yes, I'm calling a "character" twice - because I wanted to have the program give me an error. Calling a "character" that's already on stage, or telling one that's absent to exit, will cause great grief to the parser/compiler.

Length 39 snippet

the sum of a fat lazy pig and yourself!

The full instruction is more better looking that this, I'll give you that, but... here's our first arithmetic operation! What does it all mean, actually? Well, pig is a dirty animal (albeit tasty), so it's equivalent to -1, has two adjectives, meaning fat lazy pig equals 2*2*(-1) = -4. But what about yourself? It's a reflexive pronoum, not a name nor an adjective. Well, remember that SPL is based on dialogues between "characters"; thus, yourself refers to the other "character" on stage. So, we arrive at the end and we discover that "the sum of a fat lazy pig and yourself" is, in fact, -4 + x.

Length 40 snippet

the sum of a squirrel and a white horse.

Yes, another sum, but this one is simpler than snippet 39. This is merely 1 + 2 - 3, if my math is correct.

Factoid (still with me after these forty snippets of artistic fluff? You deserve a prize.)

SPL, in its version 1.2.1, can be downloaded here.

Length 41 snippet

Juliet:
 Speak thy mind!

[Exit Romeo]

Sometimes, "characters" are only called on stage to have their value changed - which, on a real play, would be something quite bizarre. Anyway, here, Juliet makes her beloved Romeo print his stored value, after which he exits the stage.

Length 42 snippet

Speak YOUR mind! You are as bad as Hamlet!

Again two instructions in one line (we can have multiple, but the snippet length doesn't allow it yet); here we have a "character" telling another to output its value and assume whichever value Hamlet has. Confusing? Mayhap.

Length 43 snippet

Am I as horrid as a half-witted flirt-gill?

Juliet asking this doesn't mean she has low-esteem (although it might in real-life); it's simply another if, like snippets 23 and 37. Oh, I almost forgot: this translates to if (Juliet == -2).

Length 44 snippet

You are as evil as the square root of Romeo!

Yes, square roots are evil, didn't you know? Anyway, this instruction is straightforward enough to understand what it does: attributes the "character" being spoken to the value of the square root of the value stored in Romeo.

Length 45 snippet

Hamlet:
 Art thou more cunning than the Ghost?

Snippet 37 properly written with the character who's speaking the line.

Length 46 snippet

the product of a rural town and my rich purse.

Okay... anyway, SPL may be the only language in the world that allows you to multiply towns with purses. This means (2*1)*(2*1) which, if I'm not very mistaken, is equal to 4.

Length 47 snippet

Romeo:
 Speak your mind.

Juliet:
 Speak YOUR mind!

I'll give you that: it may be one of the most bizarre dialogues in history. But it's what you get when you choose a weird language to showcase. Romeo and Juliet are telling each other, in short, to output their values.

Length 48 snippet

You lying fatherless useless half-witted coward!

Translating it directly, 2*2*2*2*(-1). -16, right?

Length 49 snippet

Scene V: Closure.

Hamlet:
 Speak your mind!

[Exeunt]

An example of how to terminate a program in SPL. You can declare a scene specifically for it (although it's not required), then Hamlet asks another "character" to output their value, then they all exit the stage. And yes, it's required for all of them to get off the stage.

Length 50 snippet

Othello, a young squire.
Lady Macbeth, an old fart.

More "character" presentation, before the proper instructions. As always, the only thing that matters to the compiler is Othello and Lady Macbeth, so the rest of the line is up for grabs...

One more thing: the "characters" don't have to be related to each other in order to appear in a SPL program - so you can have Romeo, Othello and Hamlet on the same play.

Factoid (half-a-century of these things? Phew! After this I think I'm going to loathe William Shakespeare...)

The SPL to C translator, mentioned a while ago and developed by the SPL creators, was based on Flex and Bison.

Length 51 snippet

Othello:
 Recall your great dreams. Speak your mind!

(So sick of Romeo, Juliet and Hamlet... let's bring in Othello, for a change!)

Recall, as you can guess, is the key here. The "character" Othello is addressing will take a value from his/her stack, assume that value and, afterwards, will output it.

Length 52 snippet

Thou art as pretty as the sum of thyself and my dog!

Another sum. Yawn. Assuming this one is addressed to Hamlet, means that Hamlet = Hamlet + 1. Or Hamlet += 1. Or Hamlet++.

Length 53 snippet

Romeo:
 You are as vile as the sum of me and yourself!

Ah, yes, something I forgot to mention before: the speaking "characters" can mention themselves on their own lines.

Length 54 snippet

Juliet:
 Is the sum of Romeo and me as good as nothing?

Another example of the previous snippet, included in a condition. So what we have here is if (Romeo + Juliet == 0).

Length 55 snippet

Juliet:
 You are as lovely as the sweetest reddest rose.

So, here, Juliet is praising the "character" she's speaking to (let's assume it's Romeo, for Shakespeare's sake), declaring that he/she is 4. Yes, another assignation of values.

Length 56 snippet

Othello:
 You lying fatherless useless half-witted coward!

Snippet 48 properly done, with a "character". If you're too lazy to scroll up (like I'd be), this means the one being insulted is receiving the value -16.

Length 57 snippet

Romeo:
 If not, let us return to Act I. Recall thy riches!

I've already explained how conditions work on SPL on a general basis; however, a more inline analysis is needed. We don't have else in here: per instance, in this example, if the condition failed, the program would return to Act I; but if it were true, it would continue to the next instruction, which is a Recall - a pop from the stack, that is.

Length 58 snippet

Romeo:
 You are as disgusting as the square root of Juliet!

Grabbing snippet 44 and presenting how the instruction should be presented. If this was a dialogue between Romeo and Othello, then we could translate this to Java as Othello = Math.sqrt(Juliet).

Length 59 snippet

Othello:
 You are as vile as the sum of yourself and a toad!

OK, if Othello is talking to Romeo, this would be equivalent to Romeo+(-1); Romeo--, for short. Pretty basic, right? That's SPL for you.

Length 60 snippet

Is the quotient between the Ghost and me as good as nothing?

For short, if (The Ghost/Hamlet == 0), assuming the "me" belongs to Hamlet.

Length 61 snippet

Thou art as handsome as the sum of yourself and my chihuahua!

Once you peel away the layers and layers of words and insults, you notice that SPL is pretty much a basic thing, without cool functions and stuff. So we have loads and loads of arithmetic functions on the program's body. So, if this one was addressed to Juliet, it would be equivalent to Juliet++.

Length 62 snippet

twice the difference between a mistletoe and a oozing blister!

Yes, yes, more arithmetic operations. Roughly, these 62 bytes of SPL can be translated to 2*(1-2*(-1)). This would be a pretty awesome golfing language, right? Right.

Length 63 snippet

You lying stupid fatherless rotten stinking half-witted coward!

Snippet 48 outputted -16, this one is equal to -64: 2*2*2*2*2*2*(-1).

Length 64 snippet

your coward sorry little stuffed misused dusty oozing rotten sky

From what I understand of SPL, this is perfectly legit. You have a whole lot of insulting adjectives what proceed a "positive" noun. Since adjectives have no special distinction whether they're negative or not (their only value is multiplying the number at their right by two), we can have completely silly sentences like this one. Which is equivalent to 256. Because 2*2*2*2*2*2*2*2*1=256.

Length 65 snippet

You are nothing! You are as vile as the sum of thyself and a pig.

Hmm, so much hate, isn't it? So, what we have here is equivalent to y=0; y=y+(-1); Probably could have been "golfed" to You are a pig!, but heh.

Length 66 snippet

You are as beautiful as the difference between Juliet and thyself.

So, subtract Juliet from yourself, heh? This one's pretty simple to decode: Romeo=Juliet-Romeo;, assuming it's Romeo who's being spoken to.

Length 67 snippet

Juliet:
 Am I better than you?

Romeo:
 If so, let us proceed to Act V.

How most conditions work on SPL. You test the expression and, if it's true (or not: see snippet 33), you jump to another part of the program; otherwise, you'll continue on to the next sentence.

Length 68 snippet

The Ghost:
 You are as small as the sum of yourself and a stone wall!

Yes, yes, I'm getting a bit monotonous. But SPL is like that. As I stated a bit earlier, its expressions are a mixture of arithmetic operations. Thus, this is yet another incrementation - since stone wall is a neutral "noun".

Length 69 snippet

Thou art as disgusting as the difference between Othello and thyself!

Instead of a sum, we have the subtraction between two characters, Othello and whoever is being spoken to.

Length 70 snippet

You are as handsome as the sum of Romeo and his black lazy squirrel!

We return to the additions, yes - call me formulaic, heh. We translate this to Romeo + 2*2*1.

Length 71 snippet

Scene I: Dialogues.

[Enter Juliet]

Othello:
 Speak your mind!

[Exit Juliet]

A Scene can be as small as this. Juliet enters the stage, Othello tells her to output her stored value, then she gets off stage again.

Length 72 snippet

twice the difference between a mistletoe and an oozing infected blister!

One more arithmetic operation - because SPL is riddled with them. We can translate this to 2*(1-2*2*(-1)).

Length 73 snippet

You are nothing! Remember me. Recall your unhappy story! Speak your mind!

Four instructions in a row?! I'm quite proud of myself, actually. Anyway, let's assume this is a dialogue between Romeo and Juliet (and he's speaking): this means that Juliet's value starts at 0; then, Juliet will push Romeo's value into her stack of memory, pop it and output it in its entered form. Simple, right?

Length 74 snippet

You are as sweet as the sum of the sum of Romeo and his horse and his cat!

Yeah, yeah, boring example, I know. But this is X = (Romeo + 1) + 1.

Length 75 snippet

Is the remainder of the quotient between Othello and me as good as nothing?

Well, this is pretty straightforward. If your decoding skills are malfunctioning, it translates to if (Othello % X == 0).

Length 76 snippet

Thou art as rich as the sum of thyself and my dog! Let us return to scene I.

The jump from snippet 26 with an expression before it. A goto on SPL isn't always found near a condition, it can be like this - and, of course, this type of goto will always be found at the end of an Act or Scene, since instructions after it will never be compiled/performed. The first instruction is pretty simple: x=x+1.

Length 77 snippet

[Exit Hamlet]

[Enter Romeo]

Juliet:
 Open your heart.

[Exit Juliet]

[Enter Hamlet]

So, we have Juliet and Hamlet on stage; but we're in need of the value from Romeo. Thus, in order to spare the compiler from a very nasty headache, firstly we remove Hamlet from the stage (though it could have been Juliet the one to go), we tell Romeo to get on stage, Juliet gives him an instruction to output a number (see snippet 21's explanation), then Romeo gets out of the stage and Hamlet returns. Pretty straightforward and simple.

Length 78 snippet

The Ghost:
 Speak thy mind.

Lady Macbeth:
 Listen to thy heart! Remember thyself.

So, The Ghost (Hamlet's deceased father) is telling Lady Macbeth to output her value, while she orders The Ghost to read a number and push it into his stack.

Answered by Rodolfo Dias on November 19, 2021

Ruby

Created by Yukihiro "Matz" Matsumoto in 1995, Ruby is a dynamical object-oriented programming language. It's built/inspired by Perl, Smalltalk, Eiffel, Ada, and Lisp.

Matz, speaking on the Ruby-Talk mailing list, May 12th, 2000.

Ruby is simple in appearance, but is very complex inside, just like our human body

Factoid
In Ruby everything is objects, so no primitives. Parentheses are also optional. Opening up for some interesting coding, but that doesn't mean that you have to avoid them.
Is this really that readable?

puts array.delete hash.fetch :foo

Snippet 1
Use the $ to create global variables, but don't clutter the namespace please.

Snippet 2
To create a new hash, all you need to type is {}.

Snippet 3
Ruby uses nil as a false value. So no need to do var.nil? everywhere.

Snippet 4
puts is used to print a string version of an object with a new line at the end. Short for "put string". Can also be shortened to just p.

Snippet 5
To make Ruby even more powerful it handles closures. And with the use of f.call you can call/invoke a block or function. Pretty sweet. For those unfamiliar with closures. A closure can pass it around like an object (to be called later). It also remembers the values of all the variables that were in scope when the function was created. It can access those variables when it is called even though they may no longer be in scope.

Snippet 6
The snippet class C returns nil, and that is because everything in Ruby has a return value. You can even return multiple values.

Snippet 7
With the use of include Ruby support single inheritance. Making it easy to mixin modules.

Snippet 8
x||=true is one of several logical operators that Ruby supports. This one checks if x has been defined, and if not sets it to true.

Snippet 9
Fo.new(x) calls the class Fo initialize function, with the value of x. There is no constructor in Ruby so you are free to return what value you like from the .new() call.

Snippet 10
As mentioned earlier Ruby supports multiple return values, and it is easily done with return x,y. The values are returned as they are read, and if you have more return values then what you have for assigning the rest will be dropped. Using the * on the last variable will make an array and assign the rest of the return values to that array.

Snippet 11
RubyGems is the packet manager for Ruby started in November, 2003. Original a stand alone program, but as of Ruby 1.9 it is a part of the standard library. Use the code snippet gem install and the name of the package (for example 'sinatra') to install it.

Snippet 12
[1,2]<<[3,4] The command '<<' pushes or append a object to the array. In our case the array [3,4] will be pushed 'into' the array [1,2], making it 'look' like this [1,2,[3,4]]. So it does not merge two arrays.

Snippet 13
x.map{|y|y+1} The map function iterates over the array 'x' and invokes the block given, and returning a new array with the modified values. In our case it will iterate over the values in the array and increment them with one.

Snippet 14
x.map!{|y|y+1} This snippet is similar to the previous one, but calls on the function map!. The '!'/exclamation mark tells the user that this function will modify the object calling it, often called destructive or dangerous functions.

Snippet 15
The snippet ARGV[0] ||false checks if ARGV[0] evaluates to true, if not it will return the or value, false. ARGV is an array containing the arguments sent in at start time. ruby app.rb test will give you 'test' in ARGV[0].

PS: Also check out this post about Ruby

Answered by Kyrremann on November 19, 2021

Agda

Factoid:

Agda is a Haskell inspired language with even more advanced type system, that makes it possible to declare statements about programs and proof their validity. It comes with proof assistant tools, embedded into Emacs, so you can use it interactively to construct mathematical proofs.

1

_

Underscore has bunch of meanings in Agda. It can mean a wildcard, meaning you don't care about naming stuff when you pattern match. It can tell Agda to guess values or types, which it does by solving type equations. Or as a placeholder in function definitions, it can be placed nearly anywhere, so that definition of post,pre,infix operators are possible (e.g. _! can define factorial and if_then_else_ a condition clause).

2

()

An absurd pattern. Doing a pattern match on an absurd pattern tells Agda, that this pattern is impossible. Or in other words, we trying to match to an empty type (bottom ), the type with no values.

3

Set

Types and values in Agda are treated similarly. As value can be of a certain type, the type itself can be of a type of something, this something is called Set. For example 0 : ℕ : Set means that zero has type of natural numbers (or just 0 is a natural number) and natural numbers are of type Set (or natural numbers represent type or set). But it doesn't end here, because even Set has type Set₁, which has type Set₂ and all the way up to infinity (and beyond).

4

data keyword is used to define types in Haskell's GADT (Generalized Algebraic Data Types) style. Here are some examples

Empty type

data ⊥ : Set where

Boolean type

data Bool : Set where
  false : Bool
  true : Bool

Natural numbers

data ℕ : Set where
  zero : ℕ
  suc : ℕ → ℕ

5

f = f

Spaces around operators are mandatory, so we can only now construct some simple definition. This snippet is a valid definition of non-interrupting program in Haskell, but it won't compile in Agda due to the Termination check failure. Agda is a total language, meaning every program in it should terminate and there is no way to construct a valid non-terminating function. The reason behind it is that this function can be of an arbitrary type f : ∀ A → A, and due to Curry–Howard isomorphism between programs and proofs, constructing a value of any type basically means that we proved everything!

6

record

Agda has records, datatypes with single constructor. For example we can define a pair like so

record Π (A B : Set) : Set where
  constructor _,_
  field
    first  : A
    second : B

And we can define pairs now p = (zero , false) (parenthesis can be omitted) and extract fields from them: Π.first p is zero and Π.second p is false.

Also there is a convention to define a type with one element as an empty record

record ⊤ : Set where

There is only one value of type , which automatically deduced to be an empty record record {}, it can be used to define true propositions.

7

∃ n = n

For an arbitrary type of n this is just an identity function, but if it has type for example ∃ : ℕ → ℕ then it can be interpreted as a proof that natural numbers exist!

8

λ n -> n

The same identity function can be written as an anonymous function (lambda). It can be written as a 7 length snippet with instead of ->, but I can't come up with a more interesting 8-snippet otherwise.

9

λ x _ → x

This would be a definition of a constant function that returns its first argument and discards the second. A complete defintion with the most general type that works with argument types of any universe looks like this

const : ∀ {α β}
       → {A : Set α} {B : Set β}
       → (A → B → A)
const = λ x _ → x

Stuff inside curly brackets {} tells Agda that this variables are implicit and they should be decided based on the explicit variables A and B. It's possible to include them anyways like this const {α} {β} {A} {B} x _ = x.

10

Th = ⊥ → ⊤

Here I defined a theorem Th : false implies true. I can prove it by constructing a value of type Th. As I mentioned earlier a true proposition has only one value and it also represents an empty record and the proof would be just returning it

f→t : Th
f→t = λ _ → record {}

Similarly we can proof ⊤ → ⊤ or ∀ A → ⊤, so basically anything implies true propositions. Contrary to false propositions, which can't be proven without constructing a value of empty type. We can proof ⊥ → ⊥ by absurd pattern and ⊤ → ⊥ can't be proven. Therefore a complete implication table in Agda is represented in following statements

f→t : ⊥ → ⊤
f→t = λ _ → record {} -- empty record

t→t : ⊤ → ⊤
t→t = f→t -- same proof

f→f : ⊥ → ⊥
f→f () -- absurd pattern

t→f : ⊤ → ⊥
t→f = {!!} -- nothing could be written here, just a hole

11

¬ P = P → ⊥

The definition of propositional negation. You can look at it this way: if ¬ P is true then P is false and therefore should imply false (P also should be implied from false, but everything is implied from ). Given this definition it is possible to prove some theorems, like contradiction A → ¬ A → B, contraposition (A → B) → (¬ B → ¬ A), double negation A → ¬ (¬ A) and ¬ (¬ (¬ A)) → ¬ A. Note that Agda being an intuitionistic system, the double negation elimination ¬ (¬ A) → A is not a theorem: "It's not the case that it's not raining" doesn't mean "it's raining", but only that the rain would not be contradictory.

12

Usually in is written as , but I'm short of one character

x in P = P x

Types of functions from type A to some Set _ can be thought of as a usual set in maths sense, set membership therefore has type _∈_ : ∀ {ℓ} → A → (A → Set ℓ) → Set _. Empty set is then simply ∅ = λ _ → ⊥ and the universe (the set that contains every element of type A) is U = λ _ → ⊤. Other related definitions include

x ∉ P = ¬ x ∈ P
∁ P = λ x → x ∉ P -- complement set of P
P ⊆ Q = ∀ {x} → x ∈ P → x ∈ Q -- subset

13

V A : ℕ → Set

This is a simplest data declaration for vectors (lists with size). The full definition with constructors looks something like this

data V A : ℕ → Set where
    []  : V A zero
    _∷_ : ∀ {n} → A → V A n → V A (succ n)

Notice that it's a dependent type, it depends on the value of type ! Now the function like head which returns the first element of a vector can be defined without worrying about empty vector case, we just give it a type that works only with non-empty vectors like so

head : ∀ {n} → V A (succ n) → A
head (a ∷ as) = a

Answered by swish on November 19, 2021

Ceylon

Factoid

The Ceylon name is a play on the Java name (since it is a JVM language, and like many others, it secretly hope to be a better Java). Java and Ceylon (now Sri Lanka) are both islands in the Indian Ocean, one growing mostly coffee, the other growing mostly tea...

Length 1

;

Semi-colons are mandatory in Ceylon, unlike several modern languages. As said in the language FAQ, it is a compromise in syntax.
Note in that languages where semi-colons are optional (JavaScript, Scala, Lua, etc.) but where lines can be split arbitrarily, there are often cases where missing semi-colons can result in ambiguous or unexpected expressions...

Length 2

4T

is a valid literal number in Ceylon. It reads "four tera" and its value is 4_000_000_000_000. Ceylon supports, like Java, digit grouping, and unlike lot of languages, number suffixes from f (femto, e-15) to P (peta, e+15).

Length 3

A|B

is a type which is the union of two disjoint types. This means that the value with this type can be of either A or B type. Since Ceylon does not support method overloading, it allows to define methods accepting various inputs in the same parameter, or various outputs. This feature is great to indicate a value can be null (it can't by default) and to support JavaScript dynamic types.

Length 4

{C*}

Type annotation for a stream of instances of the class C. This stream can be evaluated lazily. That's actually a shortcut for the Iterable<C> type.

Length 5

value

Ceylon is strictly typed, but is able of type inference, ie. you don't have to specify the type of a local variable (or of the return value of a local function) if the compiler can infer it.
You have to spell it out for class fields, function parameters, etc.
So you can declare a local variable with the value keyword in place of the real type, the compiler will guess its type from its assignment. Note that the term "variable" isn't right here, as it will be immutable (the default of local declarations, you have to declare them variable explicitly to mutate them).
I will continue to use the term variable here, even if they are immutable...

Length 6

Float?

Type of a float variable that might be null. By default, Ceylon values cannot be null. We have to declare explicitly if null is possible in the type of the declaration itself. And then, the Ceylon compiler forces us to check if the value is null. Thus, we can never have a NullPointerException, which doesn't exists in the language! It is one of the rare totally null-safe languages (Rust is another one, with a very different approach).
Note that this type declaration is actually a shortcut for Float|Null, ie. as seen above, the union of Float and of the Null type (which has only one instance: null).
Also note that Float is a class on its own, with methods. It is optimized to the Java float primitive by the compiler, though.

Length 7

Float[]

Type of a sequence of float values which can be empty. It is a shortcut for Sequential<Float> and can be written [Float*], similar to the stream / iterable annotation. The difference is that a sequential can be indexed with the [i] notation, like an array. For the record, a Sequence<T> (or [T+]) is a sequential that cannot be empty. An empty sequential has the type Empty and is noted [], of course.
Note that seq[i] where seq is a Float[] is of type Float? ie. the result can be null, if the index is out of the bounds.

Length 8

a else b

As seen above, if a is of type A? ie. can be null, you cannot use it without checking if it is null. It cannot be done with a == null, Ceylon offers various ways to check this. The code above is one of them: if a isn't null, use its value, otherwise, use the value of b (which cannot be null, of course; we can chain the checks...).

Length 9

{BULLET}

is a valid Ceylon character: you can put any Unicode name between the braces, like {CARRIAGE RETURN (CR)} or {WOMAN WITH BUNNY EARS}.

Length 10

if(is T v)

As we seen, we can define union types, meaning that a variable can have one of several types, eg. Integer or Float (or Byte or... etc.).
If all the subtypes derivate from the same interface, we can use the methods of the parent interface.
For example, if we have ArrayList<String> | LinkedList<String> dualList, we can use dualList.size directly.
To use a method specific to one of the member of the union, you have to be sure it is of the given type. For this, Ceylon offers a mechanism allowing in the same shot to check the type, and to downcast it to the specific type: if (is ArrayList dualList) { Integer capacity = dualList.capacity; } is legal because at this point, the compiler is sure to have an ArrayList.
It is equivalent to Java's instanceof and cast in the same shot, just safer: in Java, you can cast to something else than the type you checked!
Note that is is also an operator (resulting in a Boolean) that doesn't narrow down the type. Boolean b = v is T;

Length 11

"N ``p.n``"

Ceylon has string interpolation: you can embed in a literal string an expression between a pair of double backticks. The value of the expression will replace this placeholder. You can have simple local values, field access as shown, complex expressions or function calls. You can have literal strings (with interpolation too!) inside these expressions.

Length 12

f=(A p)=>-p;

Assigns to the f variable an anonymous function defined with the short syntax (fat arrow). Functions are first-class citizens in Ceylon, they are just objects that can be assigned, passed as parameter, returned from another function, etc.
To fit in the length, I omitted the declaration of f which can be done earlier, for example: A(A) f;
Here, f returns the negation of the p parameter which has the type A.
Notice the usage of the negation operator - which must have been overloaded in the definition of A, which then must satisfy the interface Invertible<A>.
Ceylon doesn't support to define arbitrary operators (unlike Scala, where users can get crazy with this feature... :-)), nor even "true" operator overloading, but it supports operator polymorphism: operators are defined (by name, eg. negated for the unary minus) in specific interfaces (here Invertible) that classes needing these operators must implement (must satisfy, in Ceylon vocabulary).

Length 13

C<out T>(T t)

Declaration-site variance: the class C (the class keyword and the class body have been omitted for brevity) declares, in its definition, its type parameter T to be covariant, so C<Car> is a subtype of C<Vehicle> if Car is a subtype of Vehicle.
Collection interfaces (immutable by default), like List or Set are declared covariants.
Mutable collections must satisfy an additional interface with a contravariant declaration (<out T>), defining methods accepting the given class or any supertype of it: a mutable list of Vehicle must accept adding Cars.
Java is using use-site variance, like List<? extends Car>, defined on each List declaration. It is a bit more flexible but puts the burden on the users of the class, so is more cumbersome.
Since version 1.1, Ceylon also support use-site variance for Java interoperability reasons, but promotes declaration-site variance as the preferred method.
Also note the parameter list of the class: it defines both the parameters of the constructor of the class, and the corresponding fields, in the same shot! No need for these cumbersome this.t = t;...

Length 14

for(n in 0..5)

Ceylon doesn't have the classical C-like numerical for loop. Instead, it supports range definitions, and allows to iterate on them.
Here, n (whose type, Integer, is inferred) will go from 0 to 5, included. We could have written 0:6 instead (start, number of items). A range like 5..0 allows count-downs.
These notations are just syntax sugar for declaring instances of the Range<T> class. We can have ranges of numbers, characters or any other type T satisfying the Enumerable interface.

Length 15

return["",0.0];

Return statement in a function. Here, the type of the return value is [ String, Float ]. That's a tuple, of type Tuple.
A tuple is linked list (therefore a Sequence) which captures the static type of each individual element in the list.
We can then access safely each element by its index: Float v = tuple[1];; the compiler knows the size of the tuple and the type of each entry.
Tuples are a practical / compact mean to return several values from a function, where in Java we must create a Pojo (simple, often internal, class with just fields) for this.
Side note: Ceylon doesn't accept abbreviated, unreadable (IMHO) shortcuts for floats: neither 0. nor .0 are accepted, we must write 0.0.

Length 16

shared T v=T(1);

A variable or attribute of a class (field in Java vocabulary) declaration. The variable is immutable (the default) and has a visibility annotation. Unlike Java fields, attributes (and variables) don't have an implicit default value so they must be assigned at the declaration site (or must be, for attributes, in the parameter list of the class).
Note that T(1) creates a new instance of T with one parameter. Unlike Java, we don't need the new keyword.
shared is an annotation, not a keyword. Declarations are private by default, visible only in the code unit where they are declared: the class they belong to, or the package of the file where they are declared, if they are top-level.
shared extends the visibility to the parent: a shared declaration in a class is visible in the class enclosing this class, if any, or otherwise in the whole package containing the class. If a top-level declaration is shared, it is visible to everything that can see the containing package. If the package is shared, it is visible (and its shared declarations) by other packages in the same module, and by code in other modules which import that module. Works like Russian puppets...
We introduced two concepts: packages are like in Java, folders in a folder hierarchy where the path defines a namespace / visibility unit. They allow to organize code in logical groups. Unlike Java, we must declare packages in a special file named package.ceylon in the package they belong to. That's where we declare if a package is shared (or not, by default). On the other hand, we don't have to declare the package on each file of the folder...
Modules are groups of packages, also declared in their own file (module.ceylon) at the root of the package hierarchy. They must declare a version number, and must import the modules (with their version number) used in code belonging to this module. This allows modularity of the code with fine grained management of the required versions.

Length 17

assert(exists x);

Like in Java, assert throws an exception if its expression is false. But unlike Java, the compiler knows that after the assert statement, the condition is true. Here, the expression checks if x, of type T? (remember: that's T | Null ie. either T or Null), exists, ie. is not null. So the compiler accepts to use x.foo after the assert in the same block, because it known it isn't null.
exists can be used in a if too, if that's unsure. assert is used if the programmer knows for sure (except programming error!) that a variable initially null has been set to a non-null value at this point in the code. So assert is used here as a helper of the type checker of the compiler which hasn't flow analysis...

Length 18

class C(Float f){}

Declares a class and its constructor and its attributes in the same shot: the class' parameters are those of the constructor of the class, which then doesn't need to be defined explicitly. These parameters become attributes (equivalent to Java's fields), so no need for this.f = f, the syntax is streamlined, without boilerplate.
Note that a class can have only one constructor, because Ceylon doesn't support method overloading. Instead, it has parameters with default values (and therefore optional parameters), named parameters, etc.
It also implies that the class has an initializer section, containing a mix of declarations, statements and control structures. The initializer is executed every time the class is instantiated and initializes the state of the new instance of the class.

Answered by PhiLho on November 19, 2021

Bash

Factoid:

The extremely serious ShellShock bug was present in Bash since 1989, and remained undiscovered for a quarter of a century. Much of the joy of writing Bash is coming to grips with its many idiosyncracies and inconsistencies.

Length 1 snippet:

[

An alias for the test builtin, allowing code of the format if [ a == b ]; then - in reality [ is a standalone command, not a syntactical element, and ] is purely decorative (although required by [, its requirement is arbitrary and you can do away with it by using alias [=test).

Length 2 snippet:

||

Like logical or in most languages, but for processes. Will execute the command after the || only if the command before it returns non-zero.

Length 3 snippet:

x=y

Assignment. Nice and predictable... but unlike most other languages, extra spaces aren't allowed. Which is kind of funny because you can stick extra spaces pretty much everywhere else between things in bash, just not around the =.

Length 4 snippet:

$IFS

Internal Field Separator - this variable affects how Bash splits data for many built-in actions, such as iterating in for loops and populating arrays from strings. Used correctly it can be very powerful; but more often it's the cause of subtle and unpredictable bugs.

Length 5 snippet:

${x^}

Substitute the string in x, but with the first character capitalised! Such a frequently used feature that it has its own dedicated piece of language syntax.

Length 6 snippet:

x=($y)

Fill an array, x, from a string or list of elements y, splitting on whatever the IFS is currently set to - by default, whitespace. A very useful feature for advanced bash programming.

Length 7 snippet:

${x[y]}

Arrays! But wait, what's that... y is a string, not a numerical index? Yes indeed, Bash supports associative arrays! Many people don't know this. You just need to declare -A x first.

Length 8 snippet:

${x##*,}

Substitute x, everything up until the last , character (or whatever you specify). Useful to get the last field of a csv - this is something you can't so easily do with cut, which only counts fields from the left. % and %% allows the same to cut from the right; % and # were chosen for their location on the US keyboard so it would be clear which means left and which means right, but that doesn't hold much value for everyone not using a US keyboard :)

Length 9 snippet:

[ a = b ]

In most other languages, a single equals in a comparison operation would produce unintended behaviour in the form of an assignment. Not in Bash, though. Just don't omit any of the spaces, whatever you do!

Length 10 snippet:

if [ a=b ]

This is what happens if you forget about the mandatory spaces. Will not throw an error. Will always return true - even if a and b are variables that are unset, or whatever they're set to, doesn't matter - it'll always return true. Think about code like if [ "$password"="$correctpass" ] to see the fun potential of this "feature".

Length 11 snippet:

x=${y//a/b}

Regex-style substring replacement! Set x to the value of y but with every instance of a replaced with b.

Length 12 snippet:

[[:upper:]]*

Pattern matching - you aren't limited to just using the * wildcard in the shell, you can use any POSIX standard match such as alnum, alpha, digit etc.

Length 13 snippet:

function x(){

A bit of C syntax has mysteriously crept in! One of many completely different uses for curly braces, and another example of optional decorative elements to make Bash look more like other languages - either () or function can be omitted here (but not both). Also more fun with inconsistent spaces - a space after the { is mandatory, but not before the closing }, as in function x { y;}

Length 14 snippet:

echo {Z..A..3}

Yet another totally unrelated use of curly braces. Expands a range with a specified step. In this case, will produce every 3rd letter from Z to A. Useful for generating sequences without using seq, but cannot be used with variables, so has limited functionality.

Length 15 snippet:

echo {a,b,c,d}x

Another similar but not identical use for curly braces in sequence generation; prints ax bx cx dx, and is useful for generating a list of strings from a sequence or list in a single command. Again however, limited in usefulness as it can't be used with variables inside the braces.

Answered by Riot on November 19, 2021

Python 2

Now starting with the newest for your convenience! To read through length 30 starting with the earliest first, go to revision history.

If anyone has suggestions, feel free to comment.

Length 100 ?

We reached 100, hurray! Because of this impressive milestone, I have updated this showcase with a new program.

import re
def f(i):
    w = re.sub('s', '', i)
    s = re.subn('[W_]', '', w)
    a = len(s[0])
    print '%d + %d = %d' % (a, s[1], a+s[1])

Try it Online!

Taken from this old answer of mine, which was conveniently 100 bytes.

This program uses regular expressions on the input string to count the number of whitespace characters, then non-whitespace characters. It will then display the counts, and the sum total. This challenge had a source restriction, requiring the programs to have an equal number of whitespace and non-whitespace characters. Running this program with itself as input will print 50 + 50 = 100.

re.sub is the function to replace using a regex. re.subn does the same thing, but also returns the number of replacements (in addition to the string after replacement). This program also uses a format string with a tuple of parameters to print in the proper format.


Length 52:

i=0
while s[i-n:]:print(' '*n+s)[i:n+i];i+=1;i**7**7

Taken from my entry in the Fake Marquee Text challenge. s and n need to be set to a string and an integer ahead of time.

Try It Online!

Length 43:

#-*-coding:rot13-*-
cevag h"Una fubg svefg"

In Python you are able to encode the source with a specific codec. This shows how the source can be written in Rot13. The general syntax is this: # -*- coding: <codec-name-goes-here> -*-.

Here it is translated:

#-*-coding:rot13-*-
print u"Han shot first"

The u specifies that the following string literal is a Unicode string. This is necessary if you want your strings to also be in Rot13, otherwise every string in the source is easily readable despite the encryption. Alternatively, you could use .encode("Rot13") after every string (don't forget to use Rot13 on this, too.) According to this article, some alternate encodings are “base64″, “uuencode”, “zlib”, or “bz2″.

Length 33:

import cmath
print cmath.sqrt(-1)

This is Python's module for complex (imaginary) numbers. This prints 1j, since Python conforms to engineering standards and uses j as the imaginary unit, though I prefer i, which is more commonly used in mathematics, and using j and k in addition to i for the quaternions, but I digress. Read the bug/change order here (it won't be changed).

Length 30:

f=lambda n:n*f(n-1)if n else 1

Now we define our own factorial function using recursion and the ternary if-else! As far as I know, this is as golfed as it gets in Python. It could also be written this way: f=lambda n:n and f(n-1)*n or 1, showcasing a couple Python's Boolean operators (and also done in 30 characters.) See the length 15 snippet for information on the lambda syntax.

Length 29:

import math
math.factorial(7)

Finds the factorial of 7, returning 5040.

Length 25:

import math
print math.pi

Python's math module provides many useful functions and constants. Here's PI. Returns 3.14159265359. (In the code above, I counted the newline as a character.)

Length 24:

f=lambda y:lambda x:x**y

This is an example of a closure. Calling cube = f(3) will make a cubic function that can then be called with print cube(24), printing 13824.

Length 19:

print"Hello World!"

Finally, enough room to print some basic output! The space is not required here, because quotes and parentheses are also delimiters. This will only work in Python 2, since Python 3 changed the print function to be called like any other function. In Python 3, use print("Hello World!"). For more information on the print function and difference between Python 2 and 3, see What's New In Python 3.0.

Length 16:

[x*3 for x in l]

Once again, assume l is a list or any other iterable object such as a string or generator. This statement is known as a list comprehension. It is much shorter than using the standard for loop structure. Here, it returns a list with all the numbers multiplied by 3. ALSO, strings can be multiplied! So any string in the list will be added (concatenated to itself) that number of times.

Length 15:

import this #:)

This is actually a length 11 snippet, but I realized I had forgotten to showcase Python's (awesome) easter egg! Importing this module prints The Zen of Python (See Factoid.) Interesting fact: the module this.py was encoded in rot13, which I will hopefully feature later.

Length 14:

lambda x:x**.5

This defines a square root function using Python's lambda syntax for a function literal. Function literals in Python can only contain expressions, not statements. This lambda could be assigned to a variable, passed to a function, or executed in-line with (lambda x:x**.5)(9), which returns 3.0. Using exponents for a square root is an alternative to importing the sqrt function in the math module.

Length 13:

1 if x else 0

This is an example of Python's ternary if operator. This was added in Python 2.5 to discourage coders from manually implementing it with Boolean operations. Here, 1 is return if x evaluates to True, otherwise 0 is returned.

Length 12:

s=input(">")

This will print > for the prompt text and allow the user to input a value. Python 2 interprets whatever value is entered, so any string needs quotes. Python 3 changed this, so that input entered is not automatically interpreted. To enter input without interpreting it in Python 2, use raw_input(). In Python 2, input() is equivalent to eval(raw_input()).

Length 11:

eval("2e3")

2e3 is scientific notation for the float 2 x 10³. The eval function interprets and evaluates any string as an expression. In this case, it has the same result as using the literal 2e3 or float("2e3"). It returns 2000.0.

Length 10:

range(013)

This function returns a list of integers from 0 to the octal value 013, which is 11 (exclusive), meaning that the list will be [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The function takes up to three parameters similar to the slice function we reviewed earlier: range(start, stop[, step]). The difference is, with only one parameter the parameter represents the stopping value.

Note that Python 3.x has no equivalent. It's range is similar, but is actually the same as Python 2's xrange, returning a generator object instead of a list.

Length 9:

a,b = b,a

Multiple assignment. This is a simple but elegant feature, allowing you to assign multiple values at the same time. In the snippet provided, it swaps a and b. What about the order of evaluation, you ask? All the expressions to the right of the assignment operator are evaluated before any of the assignments are made. This beats many languages that require an intermediate assignment to a temporary variable.

Length 8:

#comment

You know what it is... Wait, you don't? You know, those things that let you type arbitrary text to describe a line of code, making it easier to understand? No? Oh, okay...

Length 7:

l[::-1]

Again assuming l is a list, this will return the list in reverse order. The third argument indicates step size. Since all three arguments can be negative values, a negative step size means iterating in reverse order. The empty first and second arguments show that we're iterating over the entire list.

We're getting to where we can start using some more interesting constructs!

Length 6:

l[-6:]

This is called a slice operation. If l is a list, this will return a new list containing the last six elements of l as a list. -6 represents the starting index (6 from the end), and the colon means to continue until the ending index after it (which we left blank, so to the end.) If our list contained the numbers 1 through 10, this would return [5, 6, 7, 8, 9, 10].

Length 5:

1<x<5

One of Python's awesome features is allowing you to chain comparison operators. In many other languages, this would be typed as 1 < x && x < 5. It gets even better when you consider multiple comparisons: 1 < x < y < 5 is perfectly valid!

Length 4:

0256

An integer with a leading zero is a literal octal value. This is a nice trick for code obfuscation as well. This returns the decimal value 174. In Python 3.x, the octal value would be written as 0o256.

Length 3:

`3`

Surrounding an expression in backticks is the same as using repr(), which returns the string representation of an object. The function attempts to return the string in such a way that when it is passed as an argument to the eval function, it will return the original object. It is not the same as using str(), though the results are sometimes the same. For this input, '3' is returned in both cases. This is a favorite of mine for code golf!

Works in Python 2 only!

Length 2:

[]

An empty list.

Length 1:

_

The underscore character is a much-used throwaway variable name. If you are using a Python shell (interactive interpreter), however, it holds the result of the last executed statement (and would return it again.) Also, according to this thread, it is also used for translation lookup in i18n.

Factoid: Python is a language similar to Java and C. It was built with a specific design philosophy (taken from "PEP 20 – The Zen of Python":

  • Beautiful is better than ugly
  • Explicit is better than implicit
  • Simple is better than complex
  • Complex is better than complicated
  • Readability counts

Because of these, though semi-colons are allowed as a statement delimiter, they are usually omitted in favor of using multiple lines for readability. Also, line indentation is very important!

Answered by mbomb007 on November 19, 2021

Dart

Length 17:

a.forEach(print);

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

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

Length 16:

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

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

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

Length 15:

int get x => 9;

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

Length 14:

'''a$b

 c
''';

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

Length 13:

typedef C(a);   

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

k(C c) => c;

And calling k:

k((a) => 4);

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

Length 12:

a(b()) => b;

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

a(() => 4);

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

Length 11:

int _a = 5;

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

Length 10:

A(this.x);

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

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

Length 9:

Z.blank()

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

Z z = new Z.blank();

Length 8:

main(){}

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

Length 7:

a()=>4;

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

a() {
  return 4;
}

Length 6:

a as B

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

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

Length 5:

'A$k'

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

Length 4:

true

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

Length 3:

var

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

Length 2:

{}

Dart supports map literals.

Length 1:

;

Semi-colons are mandatory to terminate a statement.

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

Answered by Pixel Elephant on November 19, 2021

Jagl

7 Characters

()(1)GF

In Jagl, F is a recursive flatten. You can have many nested arrays and it will flatten them into one. Another little trick is, if you have an array of numbers (and arrays of numbers and so on), and just want to flatten one deep, you can just use b (the sum function) to do that.

6 Characters

(1(1))

The array definition syntax in Jagl uses spaces to separate items, but in some cases, the spaces can be omitted, reducing the character count of the program. Alternatively, this could be written 1(1)G in this case, to reduce the characters even more.

5 Characters

5r[/B

Computes 5 factorial. Makes a range of 0 to 4 inclusive, increments all of the numbers by one, and pushes the product to stack.

4 Characters

1 2G

It only takes one character to encase the whole stack in an array. Alternatively, using a lowercase g would take up to 2 values from the stack and encase them in an array!

3 Characters

m%p

It only takes three characters to filter an array on the stack for all primes, and print the results

2 Characters

T~

To make a self interpreter in Jagl, all it takes is two characters! (though, it would take 6 to make it loop endlessly)

1 Character

m

The function m in Jagl is the isPrime function, so it only takes a few characters to, say, print the primes from 1 to 1000.

Factoid: Jagl was created as a high school project, and the name stands for Just A Golfing Language

Answered by globby on November 19, 2021

R

Factoid: The R programming language began as a GNU implementation of the S programming language. It is primarily used for statistics and related applications.

Note: Though not a requirement of the competition, every snippet here can be run on its own in R.


Length 32:

`[.data.frame`(swiss,3,2,drop=F)

This looks a little mysterious... and indeed it should! There's a much better way to write this:

swiss[3, 2, drop = FALSE]

That should look a bit more familiar. Here's what happens when we run either of these pieces of code:

> `[.data.frame`(swiss,3,2,drop=F)
             Agriculture
Franches-Mnt        39.7

The swiss data frame ships with R like several others we've seen so far. It contains fertility and socioeconomic indicators for 47 French-speaking provinces of Switzerland from around the year 1888. The third row is for the province Franches-Mnt, and the second column is the percent of males involved in agriculture as a profession in each province. So in 1888, 39.7% of males in the Franches-Mnt province of Switzerland worked in agriculture.

When you extract rows or columns from a data frame using the simpler notation, R is actually using [.data.frame in the background. As we saw in snippet 24, pretty much anything can be defined as a function name so long as its surrounded in back ticks, so our snippet here is legit even though the function name technically contains unmatched brackets.

The drop= argument tells R whether you want it to drop the result into a lower dimension if possible. Indeed, if we say drop=TRUE, we get this:

> `[.data.frame`(swiss,3,2,drop=T)
[1] 39.7

Where previously the result was a data frame, R now gives us a double.


Length 31:

print(fortune("hadleywickham"))

The fortune() function is from the all-knowing fortunes package, which provides a variety of wise quotes from a variety of wise folks. This snippet will provide you with the following gem from Hadley Wickham (23) by printing to the console:

That's a casual model, not a causal model - you can tell the difference by looking
for the word "excel".
    -- Hadley Wickham (commenting on an Excel chart showing student's SAT score
       increases with family income, without considering future covariates)
       http://twitter.com/#!/hadleywickham (February 2012)

Length 30:

pie(rep(1,12),col=rainbow(12))

Who doesn't love a good pie chart? The pie() function will serve you up a freshly baked pie chart based on a vector of numbers. rep() creates a vector by repeating the first element r times where r is the second argument. The col= parameter tells pie() how to color the slices. The magical function rainbow() generates a vector of a specified length containing the hex codes for "equally spaced" colors of the rainbow.

What you have here is your basic "Amount of Each Color in This Chart" chart:

enter image description here


Length 29:

summary(lm(mag~depth,quakes))

There are a few things going on here, so let's take them one step at a time.

quakes is a dataset that ships with R. It contains information about 1000 seismic events of magnitude greater than 4.0 on the Richter scale near Fiji since 1964. Two of the columns in the dataset are mag, which is the magnitude of the earthquake, and depth, which is the depth of the epicenter in kilometers.

The lm() function, as mentioned in snippet 28, fits linear models. It returns an lm object, or more precisely, an object of class lm. There are two ways to specify the predictor (or independent variable) and the response (or dependent variable), and I've chosen the formula method. This takes the form response ~ predictor. Multiple predictors are specified as y ~ x1 + x2. The objects in the formula are evaluated in the context provided in the next argument.

So what lm(mag ~ depth, quakes) is doing is fitting a linear model using ordinary least squares regression where magnitude is the response and depth is the predictor. It knows what mag and depth are because we told it that they come from quakes.

summary() is a generic function used primarily for summarizing the results of fitted models. It invokes a method particular to the class of its argument. Since we passed an lm object, it's actually invoking a function called summary.lm().

Putting it all together, we get the summary of the linear model attempting to explain earthquake from earthquake depth. Specifically, this is what R spits out:

> summary(lm(mag~depth,quakes))

Call:
lm(formula = mag ~ depth, data = quakes)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.72012 -0.29642 -0.03694  0.19818  1.70014 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.755e+00  2.179e-02 218.168  < 2e-16 ***
depth       -4.310e-04  5.756e-05  -7.488 1.54e-13 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3921 on 998 degrees of freedom
Multiple R-squared:  0.05319,   Adjusted R-squared:  0.05225 
F-statistic: 56.07 on 1 and 998 DF,  p-value: 1.535e-13

Notice how the first thing it tells you is the function call? That's because the lm() function uses match.call(), just like we did in snippet 28!


Length 28:

f<-function(x,y)match.call()

R functions often like to keep track of what you tell them. Indeed, sometimes the command you've submitted is given back to you as an attribute of the returned object. (An example is lm(), which creates linear models.) Recalling the precise instructions is accomplished using match.call() within the function. This captures, or matches, the interpreted function call.

Here we've defined a function f() that takes two arguments and then tells you what it saw.

> f(1,2)
f(x = 1, y = 2)

This is primarily useful when developing functions for general use (rather than just for you), like in package development. If you want to see an example of match.call() in the wild, look at the source code for lm() by submitting stats:::lm. One of the first things it does is capture the function call using match.call().


Length 27:

install.packages("ggplot2")

This may seem trivial, but it shows one of the reasons why R is so popular: It's very easily extensible through packages. And anyone can develop and freely share their packages!

install.packages() does precisely what its name suggests. It goes a-huntin' for packages using your default CRAN (Comprehensive R Archive Network) mirror then installs them on your system where R can find them. You can also have it install packages from local source code.

Remember snippet 23 where we used the ggplot2 package? That package does not ship with R, but in just 27 characters you can make all of your ggplot2 dreams come true by installing it.


Length 26:

filled.contour(t(volcano))

The volcano dataset ships with R. It's a matrix containing topographic information on the Maungawhau (or Mt. Eden) volcano in Auckland, New Zealand. The rows of the matrix correspond to grid lines running east to west and the columns are grid lines running south to north.

For the sake of disorientation, let's swap the directions, so columns are now east-west and rows are south-north. We can do this using a matrix transpose, accomplished via t(). And why not make a contour map while we're at it? filled.contour() does just that.

enter image description here


Length 25:

pmatch("s",c("n","size"))

The pmatch() function provides the magic behind all the partial matching we've seen so far. The first argument is a string which is compared against each element of the second argument, a vector. If there's a unique match, the index of the matching element is returned, otherwise you get NA.

The snippet here is a "real-world" example of the use of this function. Think back to snippet 13 where we used the sample() function. It accepts arguments n, size, replace, and prob, but only requires the first two. In snippet 13 we used s= as shorthand for size=. What's actually going on in the background is something like this snippet, where what we've provided is compared against what's expected. Since "s" matches "size" uniquely, it's totally legit to use s= as shorthand.


Length 24:

`(`=function(x)9;2*(3-1)

A perfect example of something you shouldn't do! Ever!

You can assign characters as functions so long as you surround them in back ticks when defining the function. Here we told R that ( is a function that always returns 9 regardless of the input. Like in many other languages, ; can be used for including two commands on one line. So what we've told R is to define the function (, then print 2*(3-1).

Now, just about any person would tell you that 2*(3-1) should be 4 because you do 3-1=2, then 2*2=4. But we've told R that anything inside parentheses is 9. So while 3-1=2, we now have (3-1)=9. Then we get 2*(3-1) = 2*9 = 18.

Since awful things like this are possible, every time you submit code that contains parentheses in an expression (i.e. not a function call), the R interpreter actually goes looking for any functions called ( regardless of whether you've defined ( as a function. In general, the more you write, the more work the R interpreter does.


Length 23:

qplot(Na,y=RI,data=fgl)

Finally enough votes for a (very) simple ggplot2 example. The ggplot2 package is an R implementation of the Grammar of Graphics, created by the legendary R deity Hadley Wickham. In general the syntax is very different from the base R graphics and takes some getting used to. However, qplot() is a simpler interface to some of the core features of the package and has syntax akin to plot() in base R. But unlike many of the examples I've shown you, qplot() does not support partial matching of function parameter names.

The fgl dataset comes from the MASS package. It contains measurements of properties of forensic glass fragments. Here we're using the variables Na, which is the percent sodium (Na) by weight, and RI, which is the refractive index of the glass.

enter image description here


Length 22:

unique(presidential$n)

The unique() function returns a vector containing the unique values from its input vector in the order in which they appear in the input. The presidential dataset ships with the ggplot2 package (27). (Thanks to Jemus42 for correcting that!) Its description:

The names of each president, the start and end date of their term, and their party of 10 US presidents from Eisenhower to Bush W.

presidential is a data frame, and data frames contain columns just as lists contain items. Columns are referenced by name using $. This particular dataset has a column called name, containing the name of the president. But wait, we only specified n! Actually, this is yet another example of partial matching (13, 16), so n is totally legit.

Submitting this has an interesting result:

[1] "Eisenhower"  "Kennedy"  "Johson"   "Nixon"  "Ford"  "Carter"
[7] "Reagan"      "Bush"     "Clinton"

Notice how Lyndon B. Johnson's name is spelled... Oops.

(Note: It has come to my attention, over a year after posting this, that the Johnson typo has been fixed. RIP humor.)


Length 21:

integrate(dexp,0,Inf)

R has a built-in function for adaptive quadrature of functions of single variable over a finite or infinite interval. In R, infinity is specified as Inf for +infinity and -Inf for -infinity. The dexp() function is the probability distribution function for the exponential distribution. Since the support of the exponential distribution is [0, +infinity) and probability distributions integrate to 1, we would expect the result to be 1. Behold, an expected result!

1 with absolute error < 5.7e-05

Length 20:

deriv(~cos(x^3),"x")

R can do symbolic derivatives! This returns:

expression({
    .expr1 <- x^3
    .value <- cos(.expr1)
    .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
    .grad[, "x"] <- -(sin(.expr1) * (3 * x^2))
    attr(.value, "gradient") <- .grad
    .value
})

Looking through that you can see how it parses the function and uses the chain rule. Everything a function who took first year calculus should be able to do! The first argument to the deriv() function is an R expression (which is an actual R type) in terms of some variable, in this case x. The second argument is the name of the variable with respect to which the derivative is taken, here "x".

Want to see something really neat? Assign the above to a variable, say dx. Define a variable x as a numeric vector. Then submit eval(dx). R evaluates the derivative at x!


Length 19:

c(matrix(1,3,3),"a")

In R, c(), short for "combine" or "concatenate," creates a vector from its arguments. The elements of vectors must be of the same type and all have length 1. But instead of getting mad at you about it, R will flatten an element with structure, in this case a matrix, and cast everything to the same type.

If the arguments to c() contain only a single type, no type casting occurs, e.g. if all arguments are logicals (TRUE and FALSE), the vector will be all logicals. If it contains logicals and numbers, it will be all numbers. If it contains character and anything, it will be all character. So our snippet gives us this:

> c(matrix(1,3,3),"a")
[1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "a"

Note that the 3 by 3 matrix was flattened and the addition of "a" made everything into characters.


Length 18:

(1-1/3-1/3-1/3)==0

A lesson in machine precision. This returns FALSE.


Length 17:

example(readline)

The example() function will give you an example of how to use any built-in function. If you need to find out how to use readline(), R has a smug answer for you.

> example(readline)

readln> fun <- function() {
readln+   ANSWER <- readline("Are you a satisfied R user? ")
readln+   ## a better version would check the answer less cursorily, and
readln+   ## perhaps re-prompt
readln+   if (substr(ANSWER, 1, 1) == "n")
readln+     cat("This is impossible.  YOU LIED!n")
readln+   else
readln+     cat("I knew it.n")
readln+ }

readln> if(interactive()) fun()
Are you a satisfied R user?

Way to be modest, R.


Length 16:

acf(lh,t="part")

The acf() function returns the autocorrelation function for a time series. lh is a dataset that ships with R. Its description:

A regular time series giving the luteinzing hormone in blood samples at 10 mins intervals from a human female, 48 samples.

In this example, partial matching is being used twice: once with the function parameter and once with the string value passed to the parameter. The full parameter name is type and the recognized values are "correlation", "covariance", and "partial". Only enough of the string has to be provided to identify it uniquely, so we can use "part" for "partial", which gives us the partial autocorrelation function (PACF).

enter image description here


Length 15:

p3d(bunny,p=99)

Again we see the infamous bunny (11). The onion package gives us an even nicer way to view the most useful dataset ever, using the 3D plotting function p3d(). This calls the base graphics function persp() in the background, which takes a rotational argument phi. Using partial matching of parameter names (13), we can specify just p= in place of phi=.

enter image description here


Length 14:

stats:::rgamma

R is open source but you don't have to be a wizard to view the source code; you can just type the package name and the function whose code you want to view separated by three colons (:::). This gives you the code that defines the rgamma() function, which generates random deviates from the gamma distribution. Submitting this gives:

function (n, shape, rate = 1, scale = 1/rate)
{
    if (!missing(rate) && !missing(scale)) {
        if (abs(rate * scale - 1) < 1e-15)
            warning("specify 'rate' or 'scale' but not both")
        else stop("specify 'rate' or 'scale' but not both")
    }
    .External(C_rgamma, n, shape, scale)
}
<bytecode: 0x00000000098cd168>
<environment: namespace:stats>

Note that it uses a function .External(). This calls functions written in other languages, typically C and Fortran, the languages which comprise much of the foundation of R. Locating that source code does take a bit of wizardry. Edit: @Vlo pointed out that mere mortals can indeed view underlying C code invoked with .Internal() and .Primitive() using the pryr package. Thanks, @Vlo!


Length 13:

sample(9,s=4)

This doesn't look like much, but it exemplifies a powerful concept in R: partial matching of function parameters. The named parameters in the sample() function are size, replace, and prob, but you only need to provide enough letters of the named parameter to identify it uniquely. Thus for sample(), you can use s= instead of size= since no other parameter names begin with the letter "s". The code here selects a random sample of size 4 from the integers 1 to 9.


Length 12:

LETTERS[-pi]

There's a built-in vector called LETTERS which contains all uppercase English letters ordered alphabetically. Unlike many other languages, you can index a vector using a floating point number. Nothing too exciting happens; R just takes the integer portion. Using - preceding the index of a vector removes the element with that index from the vector. pi is a built-in constant containing--you guessed it--the irrational number π. So this removes element 3 from the vector and returns "A" through "Z" omitting "C".


Length 11:

plot(bunny)

In the onion package, there's a dataset called bunny. Plotting it gives you what may be the most useful graphic of all time:

enter image description here


Length 10:

????sample

Say you're REALLY confused about the sample() function and you desperately need help. Rather than the usual ?sample to pull up the R manual page, you pound out four question marks. R hears your plight and attempts to help...

Contacting Delphi...the oracle is unavailable.
We apologize for any inconvenience.

Alas.


Length 9:

isTRUE(1)

At first this looks to defy the convention in the rest of the R base package to separate is and the following word in the function name with a .. However, that only applies to a logical test of whether the argument is of a certain type, as below (8). In this case, we're testing whether it is TRUE, which is not a type. This uses a strict definition of TRUE, i.e. 1 is not "true" in the usual sense. isTRUE(1) returns FALSE.


Length 8:

is.na(8)

Unlike most other programming languages, . is a valid character in function and variable names. It does not denote any sort of method or heirarchy; it's just part of the name. The is.na() function checks whether its argument evaluates to NA (missing) and returns TRUE or FALSE.


Length 7:

stop(7)

This issues an error with the input as the error message. If called inside of a function, the function execution will stop. But calling it outside of a function won't stop the script. In this case, the output is Error: 7.


Length 6:

x < -1

While this may seem trivial, it displays a major criticism of the assignment operator <-: namely, the meaning changes depending on the placement of spaces. As mentioned, x <- 1 assigns 1 to x. Separating < and - with a single space as above changes it to a logical test of whether x is less than -1. For that reason, many prefer = for assignment.


Length 5:

x<<-1

Similar to <- except <<- always assigns the variable to global scope regardless of the current scope.


Length 4:

x<-1

R uses <- to assign variables in the current scope. This snippet assigns the value 1 to x.


Length 3:

!0i

The ! operator is R for "not," and 0i is the complex number 0+0i, AKA 0 in the complex plane. Submitting this statement returns TRUE since 0 is false.


Length 2:

NA

This returns the special R value NA, which stands for "not available," denoting a missing value.


Length 1:

T

This returns TRUE. In R, T and F are synonyms for the boolean values TRUE and FALSE, respectively.

Answered by Alex A. on November 19, 2021

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.

Answered by GiantTree on November 19, 2021

IBM Enterprise COBOL

Factoid: Whilst it is possible (twists and turns) to have a useful two-character program (to be the target of a CALL to a sub-program which doesn't otherwise exist yet), other than variations of the same thing, the next one would come in at 26 characters, and would be a variation which... doesn't work.

Plus that is not counting the mandatory seven blanks at the start of a line. And it would be severely abusing the language.

COBOL's not really so good for this challenge.

This is becoming interesting in itself. Although it will be a while before I can get the program to do something else, it is an interesting academic voyage of discovery.

Remembering that these are short, and abused, programs it is interesting that only valid COBOL can be ignored, if invalid it gets an S-level diagnostic, which is going too far. Some actually valid COBOL will not work without a full-stop/period, as I've noticed when trying to Golf(!) things previously.

Two characters

Excellent. Here's the two-character example. Remembering, sorry about that, that it must be preceded by seven blanks.

   ID

Doesn't look like much of a program. Certainly not much of a COBOL program. You do have to bend things a little.

Compile it, and these are the diagnostic messages you get:

 1  IGYDS1102-E   Expected "DIVISION", but found "END OF PROGRAM".
 "DIVISION" was assumed before "END OF PROGRAM". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

                  Same message on line:      1 

 1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
 Program-name "CBLNAM01" was assumed. 

That gets you a Return Code/Condition Code of eight. Normally you wouldn't generate the code for, or attempt to execute, a program with an RC/CC higher than four. However, none of those messages affect the generated code (except the allocation of a Program-name).

What does the program do? When it is CALLed, it simply returns to where it was called from, in the normal manner.

How would you use it?

Whilst developing a program, you want to check out the control flow, but you haven't written a couple of the sub-programs yet. Simply copy the loadmodule (created by feeding the object code produced into the linkeditor/binder) to the name of the CALLed program and, assuming you are using Dynamic CALLs, you have a stub which is just going to give you back control. For a Dynamically-called program, the PROGRAM-ID (Program-name) is irrelevant, so it does not matter if you accept the generated name.

An equivalent "real" program would be this.

   ID DIVISION. 
   PROGRAM-ID. Anything.

Alternate two-character (didn't know about this before)

   FD

Diagnostics

    IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found 
    in this program.  It was assumed present. 

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

Note the lack of line-number for the first two messages. This time, with an ID, there is no line-number to associate those messages with.

Three characters also didn't know

    1 A

Diagnostics

    IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found 
    in this program.  It was assumed present. 

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

This program defines a group-item (valid for this purpose) but it is discarded.

Program operates as above.

Four characters

Since it is COBOL, we should see a full-stop/period at some time. Now.

   1 A.

Even though the line is discarded, it gets one less diagnostic because the program source now ends with a full-stop/period.

Five characters

We're up to five votes, so here's a five character program that is equivalent:

   ID FD

This operates in exactly the same way as the two-character example. FD is valid COBOL, so the compiler realises there is some stuff missing. Without it being valid COBOL, there would be an S-level message, and an RC/CC of 12. With it being a valid COBOL word, but obviously out of place, the third messages shows that it is just ignored.

 1  IGYDS1102-E   Expected "DIVISION", but found "FD".  "DIVISION" 
 was assumed before "FD". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "FD". 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
 Program-name "CBLNAM01" was assumed. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

Six characters

   ID 1 A

Combining a two character and a three characters, which need to be separated.

Diagnostics similar to the five-character solution.

Seven characters

   LINKAGE

That's a reserved-word used (followed by the word SECTION) to identify the data-items which are defined elsewhere and whose addresses are made available by a CALL from another program. Its inclusion doesn't affect our existing program :-)

Diagnostics

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found
 in this program.  It was assumed present. 

 1  IGYDS1005-E   The "DATA DIVISION" header was not found.  A 
 "DATA DIVISION" header was assumed before "LINKAGE". 

 1  IGYDS1103-E   Expected "SECTION", but found "END OF PROGRAM". 
 "SECTION" was assumed before "END OF PROGRAM". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

                  Same message on line:      1 

A little more interesting this time. That "Same message on line: 1" looks odd (as the other message it is the same as is also line 1) but that is because we only have a one-line program and there are two required full-stops/periods (should be one after the SECTION which isn't there and one to end the source program).

Answered by Bill Woodger on November 19, 2021

C++

With its preprocessor, templates, lambdas, type traits and countless other complex features that no one can ever hope to understand in its entirety, C++ is rediscovered by each new generation of its standard. By exploiting its numerous ways to do things at compile time, one can write zero overhead abstractions like a library that allows physical units being attached to numeric datatypes in order to check their soundness at compile time (e.g. you can not assign the outcome of kg*m to N)

Length 1

#

Usually introducing a preprocessor statement, # can stand on a line on its own. It essentially means nothing and seems to be so unknown that most syntax highlighters I see don't know it.

Length 2

%:

Of course not everyone has a # key, so C++ is (well, it really inherited it from ancient C) generous to allow you to write it with this alternative token (aka digraph)

Length 3

??=

This is a historical course on C++. These days not necessarily valid anymore, though implementations can support them, are trigraphs. This sequence is translated into # on those systems that support it, but to not interfere with raw string literals, it is not allowed within those. Implementations may chose to drop support alltogether.

Length 4

auto

Is one of the newer (since C++11) inventions to make working with generic code easy. It is for deducing the type of an expression, and since C++14 it can even be used for deducing lambda parameters and the return type of functions.

Length 5

 catch

Is a keyword that is also known from many other languages, present in C++, but the good idiomatic C++ programmer does almost never use it. With its constructors and destructors idiomatic C++ uses a principle widely called RAII (Resource Acquisition is Initialization) or how I like to sometimes call it more appropriately: SBRM (Scope Bound Resource Management). Due to classes like smart pointers, one can tie the lifetime of dynamically allocated resources (that is not only memory!) to other objects. When those go out of scope (e.g. by a thrown exception), these objects automatically clean up resources. This allows for exception safe and easy to use code that doesn't need to use catch.

Length 6

[](){}

[]{}()

As stefan mentioned in the comments, you can use []{} as the shortest lambda object, thus this is the shortest form to call a lambda. The following text is for the old version:

is probably the shortest form of a lambda. Lambdas in C++ are objects (of implementation defined type) that are able to capture part of the scope they are created in (the [] syntax controls this), and are callable (the () syntax controls this). Their code (The {} part) has access to these variables as if they were within their scope. With their optional return type deduction and auto parameter deduction introduced in C++14, they are the tool to use for all the standard library algorithms that expect a callable (e.g. the third std::sort parameter).

Length 7

virtual

Is the keyword to start using runtime polymorphism in C++, one of the basic blocks of object oriented programming. This follows the "don't pay for what you don't use" principle, wheras in other languages all functions are virtual by default. Being a multi paradigm language, it might be a surprise for people thinking "C++ is object oriented" to see programs or libraries that make almost no use of this keyword, e.g. because they follow the generic programming principle.

Length 8

override

Working together with the virtual keyword, override is one of the later additions to C++ to make the compiler do more work for you. By using it, you express the intention of overriding a virtual function in the base class, and the compiler will error out if you did a mistake and that class doesn't have the specified function. In general it is considered good style if your code expresses the intention, rather than fiddle with bits.

Length 9

constexpr

Being also a later addition to C++, constexpr allows the programmer to express for functions or variables, that they are known at compile time and should be computable at compile time. This allows these functions to be used in contexts that need compile time expressions (e.g. as template parameters or array sizes). Many standard library functions (if possible) are already constexpr so they can be used here.

Length 10

for(i:c){}

Is a complete loop over a container, or container like construct that supports std::begin and std::end to get iterators (that includes C style arrays). It is basically equivalent to for(auto __i = std::begin(c); __i != std::end(c); ++__i){ auto& i = *__i; }. This allows for easy looping in generic code.

Length 11

void f()&&;

Is a new way to declare member functions and the properties on the object they can be called on. In previous versions of C++ we only had the ability to chose void f() const; to tell the compiler to be able to call the function on const objects (thus without the const you can not call them on non-const objects). The same way we now have the && syntax for r-value references being used to be able to call those functions on rvalues.

Length 12

int main(){}

This is probably the shortest complete program that you can compile link and run. It will do nothing and return 0. This return is one of the many special cases you can encounter in C++. Normally returning nothing is undefined behaviour, but for the entry point function main, returning nothing means returning 0.

Length 13

auto f()->int

is a rather new way to declare the return type of a function. Normally you would not do this if you already know the type, but there are plenty of situations in generic programming where the type depends on template parameters and the variables you use. Doing it this way allows for a somewhat easier access to these parameters as in template<class T> auto f( const T& t ) -> decltype(t.foo()) instead of template<class T> decltype(std::declval<T>().foo()) g( const T& t ) { return t.foo(); }

Answered by PlasmaHH on November 19, 2021

Regex

Length 2 snippet

[]

JavaScript: An empty character class that doesn't match anything.

PCRE, Java, Python re, Ruby (tested on version 2.0): Syntax error.

Length 1 snippet

.

., called dot-all, is available in all flavors I had a chance to look at.

What does it match?

I̧n͟ g̨͜e҉̡͞n̵͢e͜͝r̷͝a͘l̢҉,̡͟ ̴̕̕.̸̴̢̛́ ̸̡̢m͞ąt̴̨c͞h̛e͢͡s̶͘ ͘a҉n̛͜͠ỳ̸ ͢c̵̡hár͘͝a̕͢ćt͘͠e͏̀͠r̷̀ ̴̕͢ex͝͞͞c҉ep̀t̛ ̕f̴҉o͟͜r̴͢ ͞n͏ę͟w̢̕͜ ͡l͝i̸̧n͢͡e̶.͟

Java Pattern: In default mode, dot-all matches any code point, except for these 5 code points rnu0085u2028u2029. With UNIX_LINES mode on (but without DOTALL), dot-all matches any code point, except for n. With DOTALL mode on, dot-all matches any code point. From Java 5, Pattern operates on code point, so astral characters are matched by dot-all.

Python re (tested on 2.7.8 and 3.2.5, may be different on 3.3+): In default mode, dot-all matches any UTF-16 code unit (0000 to FFFF inclusive), except for n. re.DOTALL lifts the exception and makes . matches any UTF-16 code unit. In these versions, re operates on UTF-16 code units, so . only manages to match one code unit of characters in astral plane.

.NET: Same as Python. The dot-all mode in .NET is called Singleline.

JavaScript (C++11 <regex>): In default mode, dot-all matches any UTF-16 code unit, except for these 4 code points nru2028u2029. With s flag on, dot-all matches any UTF-16 code unit. JavaScript also operates on UTF-16 code units.

PCRE: Depending on build option, dot-all can exclude r, n or rn, or all 3 CR LF sequences, or any Unicode newline sequence in default mode. In default mode, the engine operates on code unit (can be 8, 16, or 32-bit code unit), so dot-all matches any code unit, except for the newline sequences. In UTF mode, the engine operates on code point, so dot-all matches any code point except for newline sequences. The dot-all mode is called PCRE_DOTALL.

PHP (tested on ideone): PCRE, compiled as UTF-8 library and n is the only newline sequence by default. Dot-all mode is accessible via s flag.

Postgres: In default mode, dot-all matches any code point without exception.

Ruby (tested on version 2.0.0): In default mode, . matches any code point except for n. Dot-all mode is accessible via m flag (!).

s flag is used to indicate Windows-31J encoding in Ruby.


Factoid

Ŗ͞e̡͟҉ǵ͟͢e̴̢͘͡x̡́͞ ̛̀҉҉̢c҉̷̨a̸̛͞n҉̛͠ ̷̸̀p̴͠͡҉̵ą̧͜͢r̸̸̷̢͝s̢̀͡e̷̷̷͘͞ ̨̧̀H̨̧͜͜T̷͞M̷̛͜L͢.̴̡́ Repeat after me. R̶̶̢̧̰̞̲̻̮̳̦̥ͭͯ́̓̎͂̈ͯͤ̇͊͊͟ĕ̱̹̩̪͈͈͍̗͎̝͚̽̈́ͨ̐̽ͪͮ̍͂͐ͮͧ̔̏̓ͣ̀ĝ̵̢̢̖̤̜̭͔͊͒ͦ͛ͤ͗ͬͧͪ̾͘͟eͦ̄ͭ̑̾҉̨̨̝̬̹̘̭͔͟͢x̣̻͓̠͈͕̥̜͚̱̝̫͚̳̾̍ͦ̑̈́̋̌̉̎͊ͮ͗̄̆̒́̚̚ͅ ̸̦͈̥̬̺͇͂ͧͧ̃͐̎ͮ̌ͤ̈́̒̆ͣ̈́̏̔͊̐̀ç̨̬̪̳̦͎̖͕̦͔ͨ̃̿̓̈́ͅȁ̸̳̺̠̭ͮ̎̓̐͘̕͜͡ņ̨̫͔͍̬̤̘͎͚̣̟̦͍̜ͭͭ̈́ͦ̈́̽͗ͥ̑͝͡ ̸̛̖̝̻̻͎̍̄ͭ̓ͨ̋͋̈́͗̌̇ͤ͋ͬ͘pͪ̒̍ͫͤͭ͊ͮ̇̿̆̐̄̎͌̚͏̧͏͇̼͚̰͓̲͕̰̖̘̟̞̺̲ḁ̛͇̫̻̉̊ͣͭͤ̇ͨ́͘͠rͦ̂̈́̆͑͊ͣ̊ͮ̉̉͆ͧ̒͛̐̋̚͏̴̭̫̞̯̘̖͍̼̖̜̞̖̩͕̹̻̮̗͜͡͞ͅs̟͈̺͖̦̟̙̦͖̤ͬ̋͌̄͂ͩ̓̐̔̓͌̾̀̈͊̊ͤ̀̚eͫ̐͒̽ͯͫͨ͏̨̡̦̤̙͍̙̪̝̮̤͎̭̖̪̻͙͍͖͉̀́ ͉̭̫̰͔̝͓̼̮͚̻͎͎͉̐͗͗͊̇ͣ͒͗͑̆͐̎̐̀ͬ͛ͮ͝H̢̥͕̼͓̫͙̺̼̮ͣͦ̍ͨ͒̔̌T̪̲̦̻̦͖̞̤͒̑ͭ̐̑̃ͭͣ͐̎̒̉͊̀͜͜M̞̪͇͕̩͉͗ͧ̌ͯ͋͂̉̍ͭ̓̇̐̌͜͠Ĺ̷̨̳̘̯͚͓͛͌ͭ̉̍.ͯ͆̊̌ͯ̇̓̏͐ͪ̋̈́͑̕҉̷̠̰̼̤̲̀́

Answered by n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ on November 19, 2021

C#

C# is a fun, crazy mix of features from Java, C, Haskell, SQL, and a ton of other languages, and it provides a lot of really nice features and APIs. It's also known around here for being pretty verbose, but we'll see what we can do!

I'll ignore the usual required boilerplate (no longer required in C#9.0):

class Program { public static void Main(string[] args) { ... } }

Length 1:

;

Commands are terminated with semicolons in C#! An empty line is perfectly valid syntax.

Length 5:

x=5f;

When you specify literal numbers in C#, the compiler will assume that they are ints or doubles (based on whether they have a decimal point). If you want to use a literal float, you should specify that by appending 'f' to the number, or it will be cast at runtime, incurring a slight cost.

Length 7 (bytes):

s=@"
";

If you prefix a string literal with an @ sign, it becomes a "verbatim" string literal. Normal string literals parse escape sequences like 'n' into special characters, but verbatim literals don't, allowing you to use the backslash character without escaping it. They can also include line returns, as shown. That could save you a few bytes in golf, or make your multi-line string literals more readable. Just watch out for indentation being included in the string.

Length 8:

()=>x=y;

This expression is an anonymous function. It returns an object of type Action that can be passed around and also called like a function. Anonymous functions inherit the scope in which they were declared, and they pull any local variables in that scope with them anywhere they go.

Length 9:

(a)=>a.p;

Here's another anonymous function that uses a parameter and return value. The expression returns an object of type Func (the Func itself returns the type of a.p. You'll use Func a lot to interface with Linq.

Length 10:

enm.Any();

This is our first introduction to Linq! Linq is a set of extension methods that can be called on any object that is enumerable (implementing the IEnumerable interface) - like Array and List. IEnumerable employs lazy evaluation: it goes through the collection one item at a time, without knowing about the collection as a whole - it could even be infinite!

That's where Any comes in - it returns true if the Enumerable contains at least 1 item. Much better than calculating out the whole length.

Length 11:

var a=1.5f;

The var keyword instructs the compiler to automatically determine the type of a. a in this case will be typed as Single. Very handy for code golf, as it's shorter by far than almost any type name, though many dislike using it in production code.

Length 15:

yield return 0;

Here's a crazy statement you may be less familiar with. You know that objects can be enumerable by inheriting IEnumerable, but did you know that functions can be enumerable? Declare a function with a return type of IEnumerable, and have it yield return as many times as you want. When you get an Enumerator to the function, each call to GetNext will have the program execute all the code up to the next yield return, return that value, and then pause until you advance it again. You use yield break to end the iteration.

Length 16:

[Obsolete]int a;

This snippet shows an attribute. An attribute is a kind of tag you can stick on any declaration in your code. Some instruct the compiler to do certain things, like this one that emits an Obsolete warning if you call a. You can create your own by extending Attribute, and you can query them using Reflection (more on that later, perhaps). You can go meta and restrict what kind of declarations an attribute can be used on with the AttributeUsage attribute.

Length 17

c.Count(t=>t==3);

Here's a handy golf method. Given a Func that maps an element of the enumerable c to bool, it returns the number of elements in c for which that Func returns true. Much nicer than writing out a loop.

Length 18:

foreach(T t in c);

This is a for-each loop. With all this talk of enumerable things, this is a much-needed structure. foreach is syntactic sugar that will set up an Enumerator for c (which must be enumerable) and iterate through it one element t at a time. You can alter or examine each individual element, but altering the collection itself will invalidate the enumerator.

Length 19

c.Select(t=>t.a/2);

This is your 'map' function, for functional programming fans. Select is a nice concise way to perform some arbitrary conversion (defined by a Func passed in) on each element of an enumerable. It returns an IEnumerable that will spit out the "converted" elements when you iterate it.

Length 21

Console.Write("Hi!");

This line writes some text to stdout, and is probably one of the main reasons C# isn't used for golfing much!

Length 23

typeof(T).GetMethods();

C# supports a very powerful feature called Reflection. Reflection lets you examine the structure of your code at runtime. For example, this call will return an Array of all methods on the specified type. You can examine those methods, call them, or even modify the values of fields and properties. Attributes (see Length 16) are a good way to tag parts of your code for use with Reflection.

Length 25

from t in c select t.a/2;

Is that SQL? In C# code? Pretty close. This expression does the same thing as the one at Length 19.

Length 27

for(var l;;l=new object());

C# is a garbage-collected language, which means that any memory you allocate (using the new keyword) can be automatically released as long as no references to it exist. This code will run happily forever even though I never explicitly free the memory created. Garbage collection has costs, though - search the web to learn more.

Length 29

var e=Enumerable.Range(0,99);

Enumerable.Range is a potentially handy golf function. It returns a structure that can be enumerated and will yield each number in the range specified, in order. The second parameter is a count, not an index.

Length 31

public int pr{get;private set;}

Here, we can show a simple 'property', an OOP feature and another hallmark of C#. If you've ever used Java, you've probably made 'get' and 'set' methods for a field in order to separate their accessibility or run code when it's changed. Well, C# lets you declare that code right on top of the field, and also set separate access modifiers for getting and setting. This particular snippet automatically creates a default getter and setter, but makes the setter private.

Length 32

public static void m(this T o){}

This snippet shows a C# feature that's nice for API design. By applying the this modifier to the first parameter of a static method, that method becomes an "extension" method. Once this is declared, T.m can now be called on any object of type T as though it were actually a method of T. This can be used to add new functionality to any existing class, without modifying or even having access to its source code.

Length 38

int f(int a,ref int b,out int c){c=0;}

This method showcases different types of parameter passing you can have in C#. Unmodified parameters are passed by value. Parameters prefixed by ref are passed by reference: you can assign a completely new object to them and they will carry it back out of the method. Parameters prefixed by out are like additional return values: you are required to assign them a value in the method, and they are carried back out just like ref parameters.

Length 42

Console.Write("It is {DateTime.Now()}.");

The new C# 6 standard can save you some characters when you have to output assembled strings, using string interpolation. This feature allows you to write any expression in curly braces inside a string literal, and the string will be automatically assembled with the values of those expressions at runtime.

Length 48

IEnumerable f(){for(int a=0;;)yield return a++;}

Just enough characters now to do something with an actual purpose! This method uses some of ideas we explored above to create an infinite Enumerable that will simply return the integers, one-by-one, starting with 0. Remember that C# employs lazy evaluation with Enumerables, so an infinite sequence is perfectly valid - you can iterate as much of the sequence as you want, and break out at any time.

Length 56

int p{get{return mP;}set{mP=Math.Max(value,0);}};int mP;

Here is another example of a 'property' (see snippet 31). Here, I have actually defined different code snippets for get and set rather than using the automatic ones as before. This example demonstrates how you can use a property to validate the value assigned to a variable - here, the value is not allowed to become less than 0. Other good uses of properties include notifying an event when a value is changed, or rebuilding cached values that might be based on this one.

Length 65

int v;public static implicit operator int(Program o){return o.v;}

This feature is called an implicit cast. It's sort of like an extension method in that it is static code that operates on a specific class (see snippet 32). However, the implicit cast isn't used by calling it - it's used simply by treating a Program object as an integer (e.g. int i=new Program()). When you do this, the object will be silently converted into the type you're using it as, based on the code in the implicit cast. Best practice says to only do this when no information is lost as a result of the conversion.

Answered by BMac on November 19, 2021

Piet

Factoid

Piet is a programming language where the source code consists of images. Program flow starts with the top-left pixel and moves around the image between pixels and pixel groups until it terminates.

For legibility, Piet programs are commonly displayed in an enlarged version. In such a case the term codel is used to describe a group of same-coloured pixels that correspond to an individual pixel in the source image.

For this challenge, since Piet does not use characters, one codel per vote will be used for sample programs.

1 Codel

1 Codel

This is a valid program, it does nothing and terminates. The control flow starts in the top-left (only) pixel and has no way out, which ends the program.

The pixel can in this case be any colour for the exact same effect.

2 Codels

2 Codels

This will continually read characters from stdin and keep a running total of their unicode values (though nothing is done with this total and it is not displayed).

Progam flow moves back and forth between the 2 codels, since the only way out of each one is into the other. Commands in piet are executed by movement from one codel or region into another, depending on the difference in hue and lightness of the 2 regions. The input is the command moving left-to-right and then the add is right-to-left. On the first add command, nothing will happen since there is only one value on the stack, and the specification says that commands without enough values available are ignored.

This program is a loop that will never end, as most piet programs will be at extremely small sizes, since it takes at least a few codels to properly "trap" the program flow and end it.

3 Codels

3 Codels

This is a basic echo-type program, it will read a character at a time from stdin and print it to stdout.

Again this is an infinite loop. The program starts by travelling left-to right, which does the input then output. The program will continue to flow in the same direction whenever it can. At the light green codel the only exit is to start moving back the other way. When travelling back right-to-left it attempts to perform subtract and add commands, but the stack is empty so these become no-ops.

4 Codels

4 Codels

Prints out 2 to stdout indefinitely.

Not a particularly interesting program functionally, but now that we finally have a composite number of codels we can show off slightly more advanced flow than left-to-right. When program flow attempts to exit a codel it first tries the current direction. If it's unable (in this case due to the edge of the image) it rotates 90 degrees clockwise and attempts to exit again. In this case, the program goes around clockwise 1 codel at a time, pushing 1 onto the stack twice, adding the ones together, then outputing the result.

5 Codels

5 Codels

Repeatedly reads a character at a time from stdin and tracks the sum of their unicode values.

This is essentially the same functionality as the 2-codel version, but this challenge is about showcasing the language, and one of the cool things about piet is how you can have different-looking pictures that do the same thing.

Here we see the white codel for the first time, which allows program flow to slide across it without executing instructions. The magenta and blue codels do all the work here. Travelling from blue to red does nothing because it crosses the white codel in the middle. The 2 red ones just push the number 1 onto the stack and pop it back off as it travels left-to-right then right-to-left across them, and then across the white codel so no instruction is executed.

6 Codels

6 Codels

Again, repeating earlier functionality with a different look. This is another echo program that reads a character at a time from stdin to stdout.

Here we see our first black codel. Program flow cannot enter a black codel, so from the light magenta codel in the top-right the program will fail to exit right due to the image edge, fail to exit down due to the black codel, and bounce back left into the red codel. The blue and green codels are purely decorative, the program will never enter them.

7 Codels

7 Codels

Yet another echo program with a different look.

Here we see our first codel blocks larger than size 1. In piet, any contiguous block of codels of the same colour is treated as a single block. The size of the block does not matter except when executing the push instruction, so this program is treated exactly like the 3-codel version, except with different colours.

8 Codels

8 Codels

Reads a number from stdin and outputs the square to stdout, repeatedly.

Control flow is a basic clockwise pattern just as in the 4-codel program. Starting from the top-left, the operations in order are input, duplicate (pushes an extra copy of the top value of the stack onto the stack), multiply, output. Then it pushes the value 1 onto the stack, slides across the white so no command is executed, and then pops that 1 off of the stack when moving from the lower-left to upper-left codel. This returns it to the beginning of the program with an empty stack, and it repeats.

9 Codels

9 Codels

Adds 1 + 2 = 3, and then terminates.

Now that we have a program with greater than 2 codels in both dimensions, we can finally set up a region that will trap the program and end it instead of looping forever. The first operation moving from the red codel to the dark red region is a push of 1, then the program rotates and flows down into the light red codel in the middle and pushes a value of 2. Flowing from the light red to the light yellow executes an add operation. The bottom light yellow bar causes the program to end since there is no way for it to flow out as all the corners are blocked off.


The 1- and 2-high programs are quickly becoming ugly and uninteresting so from this point on I'm going to focus on numbers that allow at least a few codels in each direction.

12 Codels

12 Codels

Finally a program that does something that could be argued as useful (though it's still a bit of a stretch). Reads 2 numbers from stdin sequentially and then outputs their sum, and does this repeatedly.

Program flows left-to-right across the 4 coloured bars perfoming 2 inputs followed by an add command. It then moves into the lower-right codel and performs an output, and then goes left across the white region back to the start.

This could have been done in 8 codels, but since we have the extra space we can make something that's a little bit inspired by an old no-signal TV display.

15 Codels

15 Codels

Reads a number from stdin and outputs its' square.

This uses a couple of tricks to get a bit of a symmetrical look to a program that actually does something. The leftmost red bar is a different colour on the bottom codel than the rest, taking advantage of the fact that (for me at least) these 2 shades of red look very similar. the program will move from the lighter red region right into the light blue codel, and then straight across the middle of the program to the light green on the right side where it is trapped. It performs input, duplicate, multiply, and output operations.

The darker red codel, along with the medium green codels on the top and bottom of the middle column, are decorative and the program will never reach them.

20 Codels

20 Codels

Reads numbers from stdin until a 0 is read, at which point it outputs the sum of all entered numbers and exits.

We finally have enough room to do control flow in the form of the pointer operation. The 4 codels along the top perform input, duplicate, and not operations, and then another not operation moving from the magenta in the top-right to the 2-codel yellow below it. The not operation pops the top value off of the stack and pushes a 1 if the top value was a 0, and a 1 otherwise. Therefore a double-not replaces any nonzero value with a 1. Moving from the yellow bar down to the dark blue performs a pointer operation, which pops the top value off of the stack and moves the direction pointer clockwise that many times.

If the top value is a 1 (i.e. we didn't enter a zero) the direction pointer will point left, moving to the magenta codels for an add operation (which will be ignored the first time due to only one value on the stack) and then through the white back to the start of the program.

If the top value of the stack is a zero at the pointer operation, the direction pointer will not change and the program will continue downwards. Moving into the lighter blue band will pop the 0 that was entered off of the stack, leaving only the sum of the accumulated numbers. Moving into the cyan bar on the bottom will output that sum, and then end since the program flow is trapped.

25 Codels

25 Codels

Countdown! Reads a number from stdin, and then prints a countdown to 1 to stdout one number at a time. For example, if 5 is read, will print 54321.

The first operation from cyan to yellow is the input. Then the yellow is where the program "loop" starts. Yellow > Magenta > Blue is a duplicate then an output, so it prints the top value on the stack but keeps a copy. Moving down the right side, we push the value 1 onto the stack then perform a subtraction, decreasing our entered value by 1. Next is duplicate, not, and another not moving from the light magenta in the bottom-right to the dark yellow beside it. This is the same zero/nonzero check as the previous program. Moving left into the light blue codel performs a pointer operation, that will either move left into the dark cyan to end the program if we're done, or up to the yellow to re-start our loop without the initial input but the original value decreased by 1.

All 3 of the red codels are decorative and could be any colour.

30 Codels

30 Codels

Fibonacci generator. Prints out terms of the Fibonacci sequence to stdout and doesn't stop.

This is the first introduction of the roll operator, as well as the first time that a region size bigger than 1 is used with the push operator to get a specific value onto the stack.

As always starts in the top-left moving right. The first 2 operations push a 1 onto the stack and then output it since the Fibonacci sequence starts with two 1s, but the main program loop will only print 1 once. Then it pushes 2 more 1s onto the stack to end up in the dark magenta in the top-right to start the main program loop.

Moving down the right side we duplicate and output to print off the next term of the sequence, then duplicate again to get a copy of the current sequence value. Moving left across the bottom executes 2 push operations. Since the light red region in the bottom-right is 3 codels in size, the first push will push a 3 onto the stack instead of a 1.

Moving up into the light blue is a roll operation. This pops the top 2 values off of the stack and performs a number of rolls equal to the first value popped, to a depth equal to the second value popped. In this case, it will perform 1 roll to a depth of 3. A roll to depth n takes the top value of the stack (our duplicated current value) and buries it n places deep. Our stack is only 3 deep right now so it will bury the top value at the bottom.

Moving up once more performs an add operation adding together the current sequence value with the previous sequence value. Our stack now has the next (new current) sequence value on top, and the last value below it. The program now moves right across the white into the dark magenta to start the loop again.

The yellow pattern in the middle is never used.

54 Codels

54 Codels

Prints "hi!" to stdout

Not a particularly long message, but printing in piet takes a surprising amount of room. Printing is done by using unicode values, and integers are pushed onto the stack by using the size of the region that is being exited. Since we have a very limited number of codels for this challenge, we use some math to get up to the printable range we want.

The program starts with a push of 5 from the cyan region on the left. From here, it flows right along the top with 6 duplicate operations to prime the stack with a bunch of 5s. Next is push 1, subtract to put a 4 on top of the stack, then 2 multiply operations to put 4*5*5=100 on top of the stack. Then a duplicate for 2 100s.

Now the program bounces off of the black and starts working leftwards along the bottom. Push operations of 3 and 2 and then a roll to bury the 2 100s under a 5. Next is push 1, subtract, and add to get 100+5-1=104 on top of the stack, which is unicode "h". Next 2 operations are push 1 and pointer to get around the corner and start moving right along the middle, and then output to print "h".

Next is add 100+5=105 on top of the stack, and output to print "i". The stack now contains two 5s. Push 1, add, multiply gives (1+5)*5=30. Finally push 3 and add for 33, and output for the trailing "!". The program then goes right through the remaining white space to end in the green on the right.

Answered by Spencer on November 19, 2021

Forth

Forth has only two types, ints and floats (and the floats are optional!) but it still manages to have chars, strings, long long ints, pointers, function pointers, structs, and more; it's all in how you use it!

Length 1

.

The . command (or "word" as we call it) prints out the integer value on top of the data stack; if the stack is empty, you get a runtime error. It also remove the value from the stack — upvote to see how we can keep it!

Length 2

.s

The .s word displays the values currently on the stack, without removing any of them. It also displays the total number of values. In Gforth, .s is limited by default to only showing the top 9 values; maybe we'll find out how to show more?

Length 3

see

Type see followed by any Forth word to see that word's source code. Most Forth words are defined in Forth itself, and only a few primitives are defined in assembly.

Length 4

1 0=

Did I mention that Forth is a stack-based language with postfix operators? Typing 1 0= pushes 1 onto the stack and then executes the 0= word, which pops the top value off the stack and pushes true if it equals 0, false if it doesn't. 0= is a convenience word for 0 =; there are several shorthand words like it for common value+word combinations, like 1+ and 0<>. Moreover, while false in Forth is 0 and any nonzero value is true, the built-in test words return true for true results, and true goes all the way — it's the value with all bits set, i.e., -1!

Length 5

-1 u.

Push -1 onto the stack, then pop it off and print it as an unsigned integer. This can be used to quickly see the maximum value for an unsigned int on your version of Forth (but not the maximum integral value that it natively supports!). You may be asking, "How do we know when an int should be printed with . and when with u.?" Answer: . when it's signed, u. when unsigned. "That's not what I meant," you say. "How do we know when the value on top of the stack is signed and when it's unsigned?" Answer: You're the programmer — that's your job! You have to know whether each integer on the stack represents an int, an unsigned int, an int*, a char*, a function pointer, or other, or else you get the demons in your nose. Forth's not going to keep track of that for you; what is this, C?

Length 6

." Hi"

Prints Hi. ." is a Forth word (which, like all Forth words, must be followed by whitespace or EOF) that reads the input stream up through the next " and prints out any bytes in between. If you put more than one space after the .", all but the space immediately after the ." will be printed. Escape sequences are not supported (so you can't print a string with a " in it with ."), but Gforth adds ." to the language, which does support them.

Length 7

: + - ;

You define your own words in Forth by writing a colon, the name of the word, the words that you want your word to execute, and a semicolon. A word can be any sequence of non-whitespace characters (whitespace is how Forth tells where one word ends and another begins, after all), even punctuation, and even operators (which are just words, after all). The above snippet redefines + to mean -, so now whenever you try to add, you subtract instead. Any pre-existing words that use + are unaffected, as they store a reference to the original definition of +.

Note: Some words do different things inside definitions of other words than they do outside, but other than control structures, they're all pretty esoteric. Most words do the same thing inside a definition as outside, but sometimes that thing isn't obvious — : show-see see see ; won't do what you think!

Length 8

: 42 - ;

When I said a word could be any sequence of whitespace characters, I meant any sequence. No, Forth does not have a word for each individual number; numbers are just a little special. When Forth encounters a non-whitespace sequence, it first sees if it's a known word; if it's not, it tries to parse it as a number; if that fails, only then do you get an error. Defining a word that's spelled the same as a number means that you won't be able to enter that spelling of the number directly anymore without getting the word instead, but Gforth and various other Forths give you multiple ways to spell numbers anyway.

Length 9

IF 1 THEN

Finally, something familiar! Obviously, this code tests whether its argument 1 is true and, if so, executes whatever's after the THEN, right? Wrong. When execution reaches the IF, the value on top of the stack is popped off, and if that value is true (i.e., nonzero), execution continues with whatever's inside the IF ... THEN and then whatever's after the THEN; if the value is zero, we just skip straight to after THEN. Note that, due to how these words are implemented internally (which is in terms of other Forth words!), IF and THEN can only be used inside a word definition, not in "interpret state."

Length 12

( x y -- y )

This is a comment. It goes from the ( to the next ) immediately after it. (In the interpreter, a newline can also end it.) This is not "built in" to Forth's syntax (Is anything?); ( is just another word, one that discards everything in the input stream up through the next ). (That's right — Forth can manipulate how its source code is read. Perl's not the only language that can't be parsed without executing it!) Since it's a word, you have to follow it with a space, or else Forth will complain that (x is undefined. We can also redefine ( as part of our ongoing campaign of shooting ourselves in the foot.

The comment's content is more interesting, however. This comment specifices the stack effect for some word; the part to the left of the -- lists what should be on the top of the stack before you run the word (the top is on the right), and the right side of the -- describes what the top of the stack will look like afterwards (again, the top is on the right). Common convention is to add such a comment to the source of any word you define, right after the : name bit, and there is also a very strong convention about naming stack elements to indicate their type that is even followed by the standard.

Incidentally, the stack effect shown is for the nip word. You should be able to tell what it does just from the comment.

Length 13

1 2 3 4 d+ d.

As previously indicated, a Forth value's type is all in how you use it — if you treat a value as a pointer, it's a pointer, and if that value's not a good pointer, it's your fault for treating it as one. However, regardless of what type you're treating a value as, it will always take up one cell on the data stack; the exceptions are double cell or double precision integers. These are integers that are represented by two values on the stack, allowing you to perform arithmetic with twice as many bits as usual. The more significant or higher-bit cell is placed on top of the less significant or lower-bit one, so that 1 0 is the double cell representation of 1, and 0 1 is either 2^32 or 2^64, depending on how big your Forth's regular cells are. Naturally, in order to treat a double-cell value as such, we need to use words that explicitly operate on double-cell values; these are generally just d (or ud for unsigned) followed by the name of the corresponding single-cell word: d+ for addition, d< for comparison, d. for printing, etc.

Answered by jwodder on November 19, 2021

JavaScript

This goes newest to oldest. Link for myself: [edit]
Length 52 snippet:

console.log([...new Array(5000000)].map((a,b)=>b+1))

This logs an array of five million consecutive integers to the console.

Length 51 snippet:

console.log(require('fs').readFileSync(__filename))

A Node.JS quine this time, though it would fail any "strict quine" requirements, due to reading its own source code.

Length 50 snippet:

a=new XMLHttpRequest;a.open('GET','file');a.send()

Finally! An AJAX request (using Vanilla.JS). We initialize, open, and send the request, but I ran out of room to add handlers and actually do anything with the result.

Length 49 snippet:

msg=new SpeechSynthesisUtterance('Hello World!');

Prepare a vocal "Hello World!". It'll be a little more work to actually speak it. We can also adjust the volume, pitch, rate, and accent. See Speech Synthesis API on HTML5Rocks. Not yet supported by Firefox, certainly not IE.

Length 48 snippet:

function repeat(){setTimeout(repeat,48)}repeat()

Simulate setInterval by recursively setTimeouting.

Length 47 snippet:

module.exports=function MyModule(a) {this.a=a};

NodeJS again, but the principle is the same everywhere in JS. This is a very basic constructor function, which creates an object with one property (a). Setting module.exports exports the function for use by require()-ing it.

Length 46 snippet:

canvas.getContext('2d').fillRect(46,46,46,46);

This requires a <canvas id="canvas"></canvas> element. It takes advantage of the fact that elements with IDs are populated as global variables, so the element is accessible as canvas from JS. Then we fill it with a 46x46 square at x=46, y=46.

Length 45 snippet:

JSON.parse(require('fs').readFileSync('jsn'))

Back to Node. Here, we parse a JSON file named jsn from the current directory.

Length 44 snippet:

(a=document.createElement('a')).href="/url";

Building on #39. Now we create an element and assign an attribute. It still isn't in the DOM though.

Length 43 snippet:

sq=[1,2,3,4,5].map(function(n){return n*n})

Creates an array of the first 5 squares, using map().

Length 42 snippet:

six="1+5",nine="8+1";eval(six+' * '+nine);

This works on the same principle as this, but JS lacks #define and so ends up uglier. It returns, of course, the answer to life, the universe, and everything.

Length 41 snippet:

c=function(){var i;return function(){}}()

The beginning of a closure. c is now a function (the internal one) with access to the internal variable i, but it doesn't do anything.

Length 40 snippet:

$('p').click(function(){$(this).hide()})

We are totally dropping those paragraphs and using jQuery.

Length 39 snippet:

script=document.createElement('script')

This is the beginning of adding a new external script. Create an empty <script> element, and keep a reference to it.

Length 38 snippet:

document.getElementsByClassName('abc')

Find all the the .abc elements in the document. Of course, with jQuery, it's only $('.abc')...

Length 37 snippet:

b=JSON.parse(JSON.stringify(a={3:7}))

Creates two identical, but decoupled objects, a, and b. If you would do

a={a:1};
b=a;
b.a=3;

you'd end up with a=={a:3}, because a and b point to the same object. We use JSON to decouple them.

Length 36 snippet:

(function f(){return "("+f+")()"})()

A quine. It prints its own source code.

Length 35 snippet:

document.body.style.display="none";

See #32. This one just hides the document, without overwriting the contents.

Length 34 snippet:

Object.prototype.toString.call(34)

Calling Object.prototype.toString is a good way to tell the type of an object. While 34..toString() is "34", the snippet is [object Number].

Length 33 snippet: (credit for this one goes to an anonymous user)

+0%-0.&(vu0061r=~void[{}<<!(0)])

Think this is not valid JavaScript? Better try it out... (use Chrome) ;)

Length 32 snippet:

document.body.innerHTML="hacked"

Halp! Hazxxors!eleven!!11!

Length 31 snippet:

a=[];for(i=0;i<31;i++)a.push(i)

No kidding, i have been waiting so long to be able to actually use a for loop! This one creates an array from 0-30.

Length 30 snippet:

new Date().getDay()==1?"S":"E"

First time using the ternary operator. I couldn't fit more than this in 30 characters, so we only know if today is Sunday, or something Else. :P

Length 29 snippet:

Object.keys(window).push('i')

Object.keys(window) will get an array of the global variables (properties of window). .push() will append an item to that array. Think this is the equivalent of window.i=undefined? Nope!

Length 28 snippet:

setTimeout("a=confirm()",28)

Waiting 28 milliseconds isn't so useful, except for creating a new thread.

Length 27 snippet:

document.querySelector('a')

It's a shame that DOM names are so long. I could only get a single link here.

Length 26 snippet:

JSON.stringify({twenty:6})

See #16. Now we get actual JSON - a string.

Length 25 snippet:

new Badge("Good Answer");

Assuming Badge() is a constructor function taking an argument... a Good Answer badge was just created!

Length 24 snippet:

do {alert(24)} while(!1)

I actually don't use do..while very much at all, but some do. If this was an ordinary while loop, it wouldn't alert anything, because it's always false. do..while will always run at least once though, so we do get to see 24.

Length 23 snippet:

window.parent==self.top

These all refer to the same object, generally known as window. If you call a function normally, there's also this. That's 5 ways of accessing the global object!

Length 22 snippet:

for(i in self)alert(i)

Alert all the global variables. It happens to be that self==window. (See the next snippet.)

Length 21 snippet:

"2"+1==21 && 2+1=="3"

Oh look, it's JS's casting rules again. This statement is true, btw.

Length 20 snippet:

Math.random()<.5?0:1

Pick a random number from 0-1, and round using the ternary operator. Though it would be easier to use Math.round...

Length 19 snippet:

[1,2,3].map(i=>i*i)

This one is new. Like, really new. It uses ES6 arrow functions to compute the squares of 1, 2, and 3. Currently, it only seems to be supported by Firefox.

Length 18 snippet:

location.href="/";

Like #15, but this time, it goes to the PPCG homepage, not SE.

Length 17 snippet:

(function(){})()

It's the snippet from 14, but better! Now it's an IIFE.

Length 16 snippet:

obj={not:'json'}

This explains one of my pet peeves. This is an object, not JSON! JSON is a data-interchange format based on JavaScript objects, but taking a more strict format.

Length 15 snippet:

open('//s.tk/')

Imagine that. Open up the SE homepage, using the http://s.tk/ redirect.

Length 14 snippet:

function f(){}

W00t! Functions! Too bad there's no room to do anything.

Length 13 snippet:

Math.random()

Generate a random number from 0 to 1. Want to define your own limits? Tough luck. (Not really, it's easy.)

Length 12 snippet:

new Date<=12

This statement has never been true in JS. JS wasn't created until '95 (see factoid), long after 1/1/1970 00:00:00.012.

Length 11 snippet:

Math.PI*121

The area of a circle with radius 11.

Length 10 snippet:

if('j')9+1

In case you haven't noticed, i like doing something with the snippet number in the code. This one returns 10, and uses j, the tenth letter of the alphabet.

Length 9 snippet:

[9].pop()

Make an array with one item. pop goes the weasel 9.

Length 8 snippet:

document

The basis for all DOM work. But we can't do anything, because it's too long. :( Go jQuery!

Length 7 snippet:

alert()

Oh boy! A function call! Finally getting to be able to do stuff!

Length 6 snippet:

var x=6

Based on #3. Much better though, because now the global is explicit. :P

Length 5 snippet:

[][5]

Even shorter than void 0 to get undefined. BTW: ''.a is even shorter; only 4 characters.

Length 4 snippet:

+"4"

This will create the number 4 out of the string "4". You can reuse these exact same 4 characters in a different order to do the opposite!

Length 3 snippet:

x=3

Oh dang, we just made an implicit global variable...

Length 2 snippet:

{}

What does this do? If you said creates an object literal, you're wrong. It's actually an empty block. Open up a console and try it! It returns undefined, not {}.

In 2018, {} in Chrome's console actually returns an empty object.

Length 1 snippet:

1

That's it. Any number is a valid JS expression.

Factoid: JavaScript was originally called LiveScript. It was changed to JavaScript to capitalize on the popularity of Java, at the time (1995). Personally, they should have kept the old name; JavaScript has been a source of confusion since. Fact is, Java and JavaScript are about as similar as "car" and "carpet".

Answered by Scimonster on November 19, 2021

Prelude

Prelude is an esoteric language with 9 instructions, plus the numeric literals 0 through 9. It was created as an ASCII representation of a music-based language called Fugue, which for some strange reason has not been implemented.

Prelude

Length 5

 v
^#

This is a 2-dimensional code snippet, so I'm not sure if the newline should count. Anyway, what it does is to duplicate the top of the first line's stack. The ^ instruction makes a copy of the top of the above line's stack. v copies the top of the below line's stack. # destroys the number on the top of the stack.

Length 4

3(5)

Everyone loves a stack overflow. The above code pushes infinite amounts of fives onto the stack.

Length 3

9()

This program creates an infinite loop, because infinite loops are very important. 9 pushes the value 9 onto the stack. () is a loop that repeats as long as the top value on the stack of the line where ( is is nonzero.

Length 2

?!

This handy utility finds the ASCII value of a character. The ? command inputs one character and places it atop the stack. At least with the default behavior of the official Python interpreter, input is character-based and output is numeric.

Length 1

!

Prelude is a stack-based language in which each line of the program has a separate stack. The stacks are conveniently supplied with an infinite amount of zeroes. ! is an instruction which outputs the top of the stack. Thus, the program ! outputs 0.

Answered by feersum on November 19, 2021

Matlab

Snippet 26 - iterate over matrices

This is something I just recently discovered. Usually you iterate over a given vector in for loops. But instead of vectors, you can also use matrices (rand(10) produces a 10x10 matrix with uniformly distributed numbers between 0 and 1).

for k=rand(10);disp(k);end

This then displays one column vector of the random matrix per iteration.

Snippet 25 - easy plotting

We know plotting is easy in matlab, but there is a super easy function ezplot (E-Z get it? It took quite a while until I finally got it, as I spelled Z always as sed instead of c, whatever...) Everyone likes elliptic curves:

ezplot('y^2-x^3+9*x-10.3')

elliptic curve

Snippet 24 - integration

The old fashioned word (but still in use in numerical computation) for integration is 'quadrature', can you guess what the result of the following one is?

quad(@(x)4./(1+x.^2),0,1)

Snippet 23 - images

Of course Matlab is also very popular among scientists who have to work with images (e.g. medical image analysis), so here is a very handy function. First argument is the image, second the angle and the third optional argument here tells the function to crop it to original size.

imrotate(rand(99),9,'c')

here

Snippet 22 - music

load handel;sound(y,Fs)

It will sound about like this (youtube link)

Snippet 21 - differentiate & integrate

polyint(polyder(p),c)

You can easily differentiate and integrate polynomials by using those two functions. When integrating, you can pass a second argument that will be the constant.

Snippet 20 - back to polynomials

p=poly(r);cp=poly(A)

Want the polynomial with the roots in r? Easy: p=poly(r). Want the characteristic polynomial of a matrix A? Easy: cp=poly(A). So roots(p) is exactly r (or a permutation of r).

Snippet 19 - another magic trick

fminsearch(fun,x0);

There are people who absolutely love this function. This basically just searches a minimum of fun with an initial value x0 (can be a vector) without any conditions on fun. This is great for fitting small models where you cannot (or you are too lazy) to differentiate the error/penalty/objective function. It uses the Nelder-Mead simplex algorithm which is pretty fast for functions where you cannot make any assumptions.

Snippet 18 - intro to polynomials

p=polyfit(x,y,deg)

Matlab has a nice solution for coping with polynomials. With polyfit you get a least squares polynomial of degree deg that approximates the points in x,y. You get a vector p that stores the coefficients of the polynomials, because that is the only thing what you need for representing a polynomial. If you go back to snippet 15, you can do the same thing by writing c = polyfit(x,y,2). So e.g. [1,-2,3] represents the polynomial x^2 - 2*x+3. Of course there are also functions for fitting other elementary, or arbitrary functions.

Snippet 17 - angles and discontinuities

unwrap(angle(c))

If you want to get the argument of a 'continuous' vector of complex numbers you often get back values that seem to have a discontinuity. E.g. angle([-1-0.2i,-1-0.1i,-1,-1+0.1i,-1+0.2i]) will get you [-2.94,-3.04,3.14,3.04,2.94] since angle only returns angles between -pi and pi. The function unwrap will take care of this! If you get a discontinuity like this, it will just add a multiple of 2*pi in order to remove those: '[-2.94,-3.04,-3.14,-3.24,-3.34]' This even works for 2d-matrices! If you just plot the argument of complex numbers with a negative real part you get the first graphics you'll get the first image, with unwrap you get the second one:

without unwrap with unwrap

[x,y] = meshgrid(-1:0.01:0,-0.5:0.01:0.5);
z = x+i*y;
imagesc(angle(z))
imagesc(unwrap(angle(z)))

Snippet 16 - scalar product

[1;2;3]'*[4;5;6]

Of course there are built in methods (like dot), but with the matrix-transformation operator ' it is as simple as that. If you do not know whether you have row or column vectors, you can just use a(:)'*b(:) where a(:) always returns a column vector.

Snippet 15 - linear least squares, the ugly method with the magic wand

[x.^2,x,x.^0]y

x is the (column) vector with the values on the x-axis, y the noisy y-values. Type c=[x.^2,x,x.^0]y and you get the coefficients of the 2nd degree polynomial. Of course you can use one of the billion builtin fit functions of matlab (how boring) why not use the magic wand?=)

x = (-1:0.1:2)';
y = 3*x.^2-2*x+1+randn(size(x)); %add some gaussian (normal) noise
A = [x.^2,x,x.^0];
c = Ay              %output: c = ]3.0049; -2.3484; 1.1852]
plot(x,y,'x',x,A*c,'-')

linreg

Snippet 14 - graphs

gplot(graph,x)

That is how to plot a graph. graph should contain a square adjacency matrix and x should be a nx2 matrix that contains the coordinates of each node. Lets make a random graph: graph = triu( rand(8)>.7) (make a Matrix that contains 0s and 1s, get only the upper triangle for an interesting graph). x = rand(8,2) then plot with some fancy styles gplot(graph,x,'k-.d')

graph (I declare this as modern art.)

Snippet 13 - meshgrid

meshgrid(a,b)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depending on two variables, you can just define a vector of values for the x-axis and one for the y-axis (a and b). Then with meshgrid, you can create two matrices of the size len(a) x len(b) where one has only the vector a as column, and the other has only the column has only the vectors b as rows. Usage example:a = -3:0.2:3;[x,y]=meshgrid(a) (if both vectors are the same, it is sufficient to just pass one.) Then you can just type z=x.^2+-y.^2 and e.g. mesh(x,y,z). This works for an arbitrary number of dimensions! So this is not only great for plotting, but also for getting all possible combinations of different vectors etc... (So, if you want to create a new code golf language, this should be in there, just make sure you use a shorter function name...)

mesh

Snippet 12 - plotting

plot(x,x.^2)

Take a vector x=-3:0.5:3 and and let plot do the rest. There are many more functions for plotting this is just a very basic one that you can use all the time. It would be already enough to write plot(v) and the data in v will be plotted against the array indices. How simple is that? If you want to style your plot, just add a string as a third argument: e.g. 'r:o' will make a red, dotted line with circles around the data points. If you want multiple plots, just add more arguments, or use matrices instead of vectors. Foolproof. plot

Snippet 11 - function handles

f=@(x,y)x+y

This is an example of a function handle that gets stored in f. Now you can call f(1,2) and get 3. Function handles in matlab are very useful for math functions (e.g. plotting) and you can define them in one line. But one drawback is that you cannot have conditionals or piecewise (and therefore no recursion). If you want this, you have to use the function statement and declare a new function, and each of those has to be stored in a separate file... (WHYYYYYY????)

PS: You'll get another funny easter egg if you type why in the console: They made a huge function that produces random messages like:

The tall system manager obeyed some engineer.
The programmer suggested it.
It's your karma.
A tall and good and not excessively rich and bald and very smart and good tall and tall and terrified and rich and not very terrified and smart and tall and young hamster insisted on it.

...which is very comforting if you are desperate enough to ask the console why...

Snippet 10 - How does my matrix look?

spy(eye(9))

As you know by now eye(9) creates a 9x9 identity matrix. spy just creates a that shows the zero/nonzero entries of the matrix. But you can also use it for displaying any binary 2d data. If you call spy without argument you'll get a nice little easter egg=)

spy on identity spy easteregg

Snippet 9

kron(a,b)

The kron function evaluates the Kronecker product of two matrices. This is very useful for discretisized multidimensional linear operators. I also used it every now and then for code golfing. You want all possible products of the entries of a and b? kron(a,b), here you go.

Snippet 8

5*ab.*b

Ok here I mixed up 3 different operator. You can multiply any matrix by a scalar by just using *. (Then every entry of the matrix gets multiplied by that scalar). But * also performs matrix multiplications. If you prepend a dot you get the .* operator, this one multiplies two matrices of the same size but entry wise. (This can also be done with division operators like / and .)

Next, the backslash operator can be used as left division (in contrast to / which performs right division as you are used to) but it is also the most powerful and characteristic operator of matlab: It performs a 'matrix division'. Lets say you have the system of linear equations A*x=b and you want to solve it for x, then you can just type x=Ab. And (you can also use / but that is less common for matrices) first quickly analyzes the matrix, and uses the results to find the fastest algorithm to perform this inversion-multiplication! (See e.g. here)

But you can also use it for under- or over-defined systems (where the there exists no inverse or where the matrix isn't even square, e.g. for least squares method). This really is the magic wand of matlab.

Snippet 7

[a,b;c]

Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expressions means that they get concatenated horizontally (that means they have to have the same height) and a semicolon means that the previous 'line' will be above the next 'line' (by line I mean everything between two semicolons. Just a simple example: a = [1,2;3,4]; b = [5;6]; c =[7,8,9]; d=[a,b;c]; will result in the same d as d=[1,2,5; 3,5,6; 7,8,9]. (Get it?)

Snipped 6

eye(7)

This function produces a full 7x7 identity matrix. It is that easy. There are other functions like nan,inf,ones,zeros,rand,randi,randn that work the very same way. (If you pass two arguments you can set the height/width of the resulting matrix.) As I will show later, you can easily create and (and in a very visual way) concatenate matrices (2d-arrays) which is sooo damn useful and easy if you have to numerically solve partial differential equations. (When you solve PDEs the general approach is discretisizig the derivative operators, basically you will get just a huge system of linear equations that needs to be solved. These matrices normally are sparse (only very few non-zero elements) and have some kind of symmetry. That's why you can easily 'compose' the matrix you need.

Snippet 5

a(a>0.5)

I hope you are not getting tired by all the ways of accessing arrays. This shows an easy way to get all elements of an array that meet some conditions. In this case you get a vector of all elements of a that are greater than 0.5. The expression a>0.5 just returns a matrix of the same size as a with ones for each element that satisfies the condition and a 0 for each element that doesn't.

Snippet 4

a(:)

This again just returns the contents of a as a column vector (nx1 matrix). This is nice if you do not know whether you stored your data as column or row vector, or if your data is two dimensional (e.g. for 2d finite differences methods).

Snippet 3

1:9

You can easily make vectors (in this case 1xn matrices) with the semicolon operator. In this case you get the vector [1,2,3,4,5,6,7,8,9]. This is also particularly nice for accessing slices of other vectors as e.g. a(2:4) accesses the second, third and fourth element of the vector a. You can also use it with a step size, like 0:0.5:10 or so.

Snippet 2

i;

A semicolon suppresses output to console. You can see it as a good or a bad thing, but I like it for debugging stuff. Any line of calculation etc. will automatically print its result to the console, as long as you do not suppress the output by a semicolon.

Snippet 1

i

Complex number are a basic number type. (Too bad many people use i as a counting variable in for loops in which case it gets overridden.)

Intro

For those who do not know, MatLab is a programming language (with nice IDE that is also called MatLab?) that is first of all intended for numerical calculations* and data manipulation. (There is an open source counterpart called "Octave") As it is only** interpreted it is not very fast, but it's strength are that you can easily manipulate matrices and many algorithms are implemented in an optimized way such that they run pretty fast when applied on matrices. It also is a very easy language to learn, but I do not recommend it as a starter language as you will assume pretty bad 'programming' habits.

*As it is a interpreted language it can be very slow for expensive projects, but you have built-in parallelization methods, and you can also use multiple computers together to run a program. But if you really wanna get fast I think you still depend on C or Fortran or crazy stuff like that. But still many implemented algorithms (matrix multiplication, solving systems of linear equations etc) are heavily optimized and perform quite well. But if you program the same algorithms in Matlab itself, you're gonna have to wait=) (Something really unintuitive when you come from other languages is that if you vectorize your operations instead of using for loops, you can save much time in Matlab.)

**You can sort of compile your programs, but that mainly converts the source code to an unreadable file (for humans), that is not that much faster when executed.

Answered by flawr on November 19, 2021

Groovy

Length 17 snippet

import bob as Bob

An import alias. No need for fully qualified names on name clash.

Length 16

@CompileStatic()

Another AST. Since it's a dynamic a language, Groovy may run slightly slower than Java. This isn't usually a problem, specially when working with databases and network, but bottlenecks may happen. Enter @CompileStatic. This AST walks the tree representation and makes every call a more pure bytecode call, giving Java-like performance to your Groovy code. Here only Extensions and AST metaprogramming work. You can add it to a class and have it fully statically compiled, and have a single method of this class being dynamic using @CompileStatic(SKIP).

Length 15 snippet

No ideas.

Length 14 snippet

{}.setDelegate

Every statement written inside a closure bears an interesting property: you can change the object which will respond to them. Also you can set the resolving order of responding objects. The topic is lengthy and i won't go over details, but this is possible:

c = {
    gimme "wot!"
}

c.delegate = new Expando(gimme: { it }) // this guy will answer the 'gimme' call
c.resolveStrategy = Closure.DELEGATE_FIRST

assert c() == "wot!"

Length 13 snippet

s ==~ /^echo/

This snippet shows the (unofficially named) dynamite operator and a variant on string declarations. Groovy has a lot of ways to declare strings; 'simple-quoted strings', "double-quoted-with-interpolation-string", """multi-line string""" and what not. But those two stand over the crowd when it comes to regex: /slashy string/ and $/dollar-slashy-string/$. No need to escape stuff, yey: /d+/!

Length 12 snippet

@TypeChecked

This is an AST Transformation. It walks on the class/method where it is annotated and checks for typing errors. Groovy was born as a pure dynamic language, although you could add types to method params and return. Later on, a lot of people coming from a Java background felt the terseness of Groovy was great, but the dynamic typing was not so, thus @TypeChecked was born. It will still allow Groovy's neat syntax, extensions and other compile-time metaprogramming to occur, but it will report errors on stuff unknown at compile-time.

Length 11 snippet

10.0 * 12.0

Oh, a mere float multiplication, you say? O noes. A digit-dot-digit in Groovy defaults to a BigDecimal, for arbitrary precision calculation. A must for financial calculations. Since operators are only allowed in Java using primitives (and something in String), using a lot of BigDecimals in Java can get messy; this snippet can be written in Java as new BigDecimal("10").multiply(new BigDecimal("20")). For floats, add an f: 10.0f, a d for double, a g for BigInteger, and a lot more.

Length 10 snippet

.metaClass

Every object in Groovy has this little property which is responsible for keeping up the MOP (Meta Object Protocol), which allows Groovy's metaprogramming: we can add methods, properties and even mix entires classes one into another to add functionality. It really shines when you are working on pure dynamic Groovy, but it is not limited to.

Length 9 snippet

a?.b?.c.d

The safe navigation operator. It stop navigating on objects which might be null. This won't throw a NullPointerException if a or b are null, but c must not be null.

Length 8 snippet

"a".tr()

The a object is a java.lang.String, but tr is not a method on Java's String. So what is going on here? Groovy features an Extension Mechanism. When the runtime finds an extension declaration in the classpath, it is automagically added to classes to enhance them. Extensions are statically compilable.

Length 7 snippet

[:]+[:]

Although the term is on pretty gray area, Groovy is a strongly typed language; the runtime makes little or no conversions between types. This snippet is really calling a well-defined method, which you can override, if needed. It can be understood pretty much as new HashMap().plus(new HashMap())

Length 6 snippet

a b {}

This snippet is parsed differently from snippet 5; from right to left. A method a receives the result of a method b receiving a closure/lambda as a param. Curly brackets {} is a closure/lambda/function, in Groovy.

Length 5 snippet

u w m

We can omit a lot of punctuation, as long as we remember Groovy's parsing order. This snippet is understood as u(w).getM().

Length 4 snippet

a*.b

The spread dot allows calling a method, or getting a property, from any iterable. This snippet is collecting the property b from every object in the list a (assuming it is a list).

Length 3 snippet

<=>

The spaceship operator! Calling this is akin to calling the compareTo method. Also chainable with Elvis: price <=> other.price ?: name <=> other.name

Length 2 snippet

?:

The Elvis operator (tilt your head sideways to see it ;-) ). Every class has an asBoolean() method. Elvis calls it (in a deep mississipi voice) and, when true, returns the value, otherwise, the else part. Checking an empty list? Easy: list ?: [1, 2, 3]

Length 1 snippet

&

An and operator. Groovy supports operator overload, but in a slightly safer way: they are overloaded through their names and only a subset of them is available. You can overload the & operator by implementing a method called and(param) in your class.

Factoid

Groovy is an alternative JVM language. It features AST Transformations, i.e., it is possible to walk the tree representation of the code and make whatever changes you'd like to it.

Answered by Will Lp on November 19, 2021

STATA

Factoid: STATA is a statistical language that is used mainly for economics modelling.

Length 1:

l

This lists all variables and every observation for each variable in a big table. It is shorthand for the list command and demonstrates that many commands can be shortened to save characters when golfing.

Length 2:

di

This is short for display, which can take any number of arguments separated by space and displays them to the console. With no arguments, it just prints a new line.

Length 3:

#d;

This is short for #delimit ; which changes the delimiter from a carriage return to a semicolon. In fact, anything but #d cr will change it to a semicolon.

Length 4:

so a

This command sorts the data in memory by variable a in ascending order.

Length 5:

cap "

The capture (shortenable to cap) command captures the errors that occur with other commands, including syntax errors. Here, the non-closed quote is an invalid command in STATA, but because capture is used, there is no error, and code can continue.

Length 6:

drop a

This command removes the variable a (and all values for a for observations in the dataset). In addition, drop can be used to specify a list of variables to drop or even a list of observations (with slightly different syntax).

Length 7:

l ///
a

Like in many languages, STATA allows comments with //. However, adding an extra / will cause the command to continue onto the next line, so here, this is equivalent to l a, which will list each observation's value for the variable a.

Answered by bmarks on November 19, 2021

C – edit

Thanks for the votes! When compared to other languages and what they can do in limited bytes, C looks obsolete, fussy and too dependent on the developer. In many ways it is: scripted and higher level languages with automatic memory management are much more expressive and quicker to production than C will ever be.

So why feature C?

The hidden secret behind all those scripting languages is that the interpreters are likely written in C (or more recently, C++ or Java). The first C++ compilers actually compiled to C code. In fact, until there's a market for a direct compiler, it's usually more cost effective to write a compiler to generate C, and then compile that.

If you're working on very small platforms, maybe even without an operating system available, you're likely working in C. These days, just about every appliance has a microcontroller embedded in it, no doubt programmed in C. When they need it small and fast, C is the way to go. (Also FORTH, for the masochists.)

Knowing C takes you as close to the metal as you can go without getting into assembler, and helps you in other languages. You have a good idea how a C++ virtual function probably works. You know when you write those pass-by-value recursive functions in PHP, that internally it's doing a lot of memory allocation and copying, so you instinctively try out pass-by-reference. Callbacks and references don't freak out C developers, maybe Haskell does though.

As Kernighan and Ritchie mentioned in their preface of the classic C Programming Language, 2nd edition, C is not a big language, and it is not well served by a big book. I'm trying to follow this advice: examples do double, triple or more duty if possible.

All the snippets are at least compilable on their own. Those that are linkable and executable are indicated as such. I know this isn't a requirement, but it makes it simpler than trying to explain the framework required to make any code snippet work.

I also tried to make sure each code snippet was as short as possible so that I'm not introducing extra spaces just to pad to a certain length. In cases where code is indented, the indents are not included in the length, just one character for each new line.

Factoid

C rocks.

Length 0 snippet

World's shortest self-reproducing program http://www.ioccc.org/1994/smr.hint

Length 1 snippet

;

C makes a distinction between compiling and linking. Many entities in C are just compiled and linked later - an example are all the static and dynamic libraries.

Other entities are just included and generate no code by themselves.

The above semi-colon will certainly compile into object code, and do nothing!

Length 2 snippet

x;

C, being an older programming language, has gone through several iterations. The earliest in widespread use was developed by Kernighan and Ritchie and abbreviated K&R. K&R C is notable for making a lot of assumptions about your code if you don't explicitly provide them.

In particular, in K&R C, the code above is assumed to be a global integer x initialized to 0. Compiling it in K&R mode will produce an object file which provides any program linking to it this variable for its use.

Length 3 snippet

??/

C is so widespread that it needs to provide compatibility features for systems which do not have all the characters it uses. The above is a trigraph for the backslash, which is used in C as a line continuation character. The above will compile, likely with a warning that there isn't a line following.

A common culture in C is to ignore compilation warnings, and many large code bases invariably have a few or more warnings when they're being built.

Length 4 snippet

f();

Again with K&R, the above is "filled out" to mean upon compilation that "There exists, with global linkage, a function f, to be provided later, which takes a fixed but unspecified number of arguments and returns an integer."

Note the fundamental differences between this and f;.

Length 5 snippet

s="";

K&R C is notable for being truly forgiving. Upon compilation, this code will provide an integer s for global linkage which is initialized to the starting address of an empty string (I think). K&R quietly handles all the coercions, including truncation if an integer isn't large enough to hold the address.

It is constructs like these which have generated many difficult-to-find bugs and provided much inspiration in IOCCC competitions.

Length 6 snippet

o=042;

A gotcha of even old timers, a leading 0 in a literal number means the digits following are in the octal base. The above code, upon compilation, will provide an integer o for global linkage initialized to decimal 34.

This feature of C has bitten many developers striving to pad their numbers to make them line up nice and even!

Length 7 snippet

f(){f;}

The above code is a function with a body. But what does it do? It retrieves the address of the function, and does nothing with it! Typically what the function will return is undefined. Nonsensical code like this can often compile without warning.

Length 8 snippet

main(){}

This represent the shortest compilable and linkable code in C. While in modern versions of C, functions usually cannot be defined implicitly, for historical reasons this restriction is relaxed for main.

This marvel of a program, which does nothing but return 0, will compile to non-negligible size, and link in various C runtime routines. You can compile and link with verbosity set to full to see what is going on under the hood.

Length 9 snippet

#define Z

A mainstay of C header files is the #define preprocessor directive. C programs compile in various stages, and in one of these stages these definitions are substituted with their actual values.

When an argument is missing, C will imply 1, so the above would substitute 1 wherever Z is used in the source code.

The above would typically be put into a header file and #included as required.

Length 10 snippet

enum{P,Q};

The enum keyword provides a sometimes type-safe way to define a series of constants. Like defines, they are often used in header files. The above code when included would define P as an integer of 0 and Q of 1.

Length 11 snippet

volatile v;

The volatile keyword is to let the compiler know that a variable may be changed by other agents and not to make assumptions that it will remain constant between accesses.

Length 12 snippet

#pragma once

#pragma once is a non-standard but widely supported preprocessor directive to indicate that the current source file be included only once in a single compilation.

The traditional and fully supported technique is to use #include guards with the disadvantages of added code and possible name clashes.

Length 13 snippet

w(){for(;;);}

There are numerous conventions in C, and one of these is how to represent infinite loops. In this case, for(;;) indicates no initialization, no exit check which defaults to 1 meaning true - i.e. don't break, and no looping code.

Sometime it's possible to do everything inside of the () and the loop itself needs no body. In this case a dummy semicolon is added at the end.

In the code above, when compiled, it will provide a function which will enter a tight busy loop - one of the no-no's in software design - and never return.

Length 14 snippet

int a[]={1,2};

Arrays in C do not need the lengths specified. The empty square brackets [] tell the compiler to "figure it out yourself". However in C, unlike other languages, there isn't a built-in way to prevent accessing an array outside of these bounds, leading to the "shoot yourself in the foot" metaphor that C is known for.

The code above, when compiled, will provide a global mutable array a of two integers initialized with 1 and 2.

Length 15 snippet

const long k=7;

The const specifer is a later addition to C borrowed from C++. A common interview question is "Does it make sense to define a variable as volatile const?". const along with enum and inline are intended to reduce the reliance on #define which has issues with type safety.

Length 16 snippet

extern void **q;

extern is used to indicate that a variable is declared elsewhere. The void * type is the standard generic type in C, meaning it doesn't need to be explicitly cast to or cast from in assignment statements. The ** operator sequence means pointer to a pointer, which often blows the minds of newbies, but is perfectly valid and often used C.

Length 17 snippet

double d=4/3-1/3;

If you were to print the above, the result would be one, and you'd think, super! Change to double d=4/3-2/3; and what's the answer? It's still one! C is using integer arithmetic to calculate 4/3 → 1 and 2/3 → 0, and 1 - 0 → 1!

Length 18 snippet

main(){puts("!");}

Finally we get to some code that actually does something! puts is a favorite of C golfers because it doesn't require a header file to use.

puts will also add a line feed to the output. Conversely, its counterpart gets will strip line feeds. One should never use gets except in very controlled circumstances - it has no protection for buffer overruns and is the root cause of many exploits.

Length 19 snippet

#include <stdlib.h>

The inclusion of header files is often a personal signature of developers. Many include lib and io regardless if they are needed. Some order the header files so the lengths are increasing or decreasing. Most put <> before "". Personally I have used this signature in my TA days to check for cheating among students: same header signature? take a closer look!

Length 20 snippet

char*p=(char*)0x300;

C is designed to be used on very low level rudimentary platforms. In some cases you might need to access special memory mapped ports directly.

In the code above the address of a port is defined as hexadecimal 300. You would access the value of the port by using *p, as in *p=0xff; to turn all bits on, or v=*p; to retrieve the current value.

Length 21 snippet

int w=sizeof(double);

The sizeof operator provides the size in bytes of a type. With variable names the brackets aren't required e.g. double d;int w=sizeof d;.

Length 22 snippet

asm("xorl %ecx,%ecx");

How asm is to be used is defined by the compiler. The above is an example of Linux gcc in-line code on an Intel platform.

The original Unix had a small but non-negligible fraction of its code in assembler. Even today, if speed is of primary concern and portability absolutely isn't, you'll see it used.

On compatible systems, the code above will compile, and it will be literally an isolated assembly instruction with no conventional means of accessing it! BTW xor R,R is a common assembly language idiom for clearing a register quickly.

Length 23 snippet

union u{char c;int i;};

A union will provide at least enough space for the largest element. You might see it used in conjunction with void * to provide a common "opaque" type in certain libraries. In this case, the union will usually be part of larger structure, with the structure having a field to identify the union type.

Length 24 snippet

/*INTS*/int i,j,k;//INTS

The original C comment was delimited as /* comment */, and borrowed the // comment to end of line format from C++.

Length 25 snippet

int main(void){return 1;}

This is the more compliant version of the length 8 snippet above. The return type and function types are specified, and it has an explicitly returned value.

The convention in C is to use a return value of 0 for success and 1 for failure, or if you want to be strictly conformant EXIT_SUCCESS and EXIT_FAILURE as defined in stdlib.h.

Length 26 snippet

typedef struct{int x,y;}P;

typedef is extremely useful, in particular, typedef struct. In modern terms you might call it "object-orientation-light".

After including the above, the code can use P as a regular type in declarations and functions, with full type-checking. Unlike C++ though, you can't define operators like +,*, or <<, hence "object-orientation-light".

Length 27 snippet

#define C(x,y)(((x)+1)*(y))

C has a convenient macro #define syntax.

A common newbie error is to omit inner and/or outer brackets, resulting in hard-to-find operator precedence errors.

Length 28 snippet

struct f{int s:1,e:8,m:23;};

C can explicitly define bit-fields which can be assigned and read and manipulated like any integer.

The above is an approximation of an IEEE single-width floating point data structure.

Length 36 snippet

f(unsigned x){return!!x&!(x&(x-1));}

In many languages, you don't need to care about how numbers are represented. In C, you need to be intimately aware of their internal representation.

The best example of this I can think of is determining if an integer is a power of two {1, 2, 4, 8, ...}. Those not familiar with C will do loops and shifts and all manner of stuff for O(log(n)) run-time, not bad, but above is a function which will do the same in O(1) run-time. I'll leave it as an exercise for the reader to confirm it works, but it really does...

The !! convention is often used to coerce an integer from non-zero and zero to 1 and 0 respectively. Many C developers like to use these kinds of tricks (often at odds of those who value code clarity).

Super keen C developers can confirm that the above will work on ones-complement and signed hardware. For those wondering, you're almost certain to be working on twos-complement hardware right now. Only the really lucky (or unlucky depending on your perspective) need to worry about this!

Length 48 snippet

#include<complex.h>
double complex c=3.0+I*4.0;

C99 includes support for complex numbers. As you can see from the code, it takes the form of a modifier for a real type. You could also use int complex c=3+I*4; but internally it coerces to a floating point type. The above code will compile in gcc using gcc -std=c99 -c length-48.c.

If you want to see more of the internals, try compiling with the -E switch. For my version of gcc, the declaration above becomes double _Complex c=3.0+(__extension__ 1.0iF)*4.0;. Note that the complex type is a significant addition to the language, not just a few cheap macros.

This is just a teaser, when we get to more than 125 characters, then we can start having some real fun with complex numbers!

Length 51 snippet

#include <math.h>
main(){double d=sqrt(sin(3.2));}

For various reasons, C doesn't automatically link to the standard mathematical functions such as sin, cos, tan, sqrt, etc. So if they're used, but not linked, the developer will be presented with the linker error undefined reference to 'sqrt', or some other error.

In gcc, the code above will compile and link using gcc length-51.c -lm.

Note sin(3.2) will return a negative number, of which the square root is not legal in the real domain. In C, a special value NaN is returned to indicate this error, which the program is free to ignore!

In C99, there are a lot of new exception handling functions to provide very safe and fine-grained control of these kinds of math errors, which just about nobody uses!

Length 63 snippet

static int w;static int X(int x){static int s=0;s^=x;return s;}

Or formatted more sanely:

static int w;
static int X(int x)
{
    static int s=7;
    s^=x;
    return s;
}

As you might have guessed, this is all about the keyword static which has more than one meaning in C.

In the first two cases, static is telling the compiler that integer w and function X are not visible outside of this file or compilation unit, i.e. they are internal.

These functions are not intended to be called externally, so they might not check the arguments for validity, and cut other corners. Because they have internal scope, you can redefine w and X in other files, and they will usually be separate.

In the last case, static indicates that the integer s retains its value between function calls. The first time X is called, s will be its initial value 7, when it is exclusive-ORed with x, the new value will be retained.

Internally, although it is implementation dependent, the usual memory organization is that s is residing on the heap, specifically initialized memory, while the argument x is residing on the stack. Where variables reside is important if you want to implement recursive algorithms, for example.

A gotcha in C are clashes with global variables. Until w and X are actually defined as static, if they are defined globally somewhere, then w and X will refer to the global entities instead.

Here q and w may not be initialized to the same value, because a global w is being used to set q:

static int q = w;
static int w;

If a global w doesn't exist, the compilation should fail.

Here q and w will be initialized to the same value:

static int w;
static int q = w;

Typically, designers will reduce name clashes by adding a distinctive prefix or suffix to their global variables and functions.

In C99, static has gained another use, e.g. int Y(int a[static 10]); which means that there is a function Y which takes an array of at least 10 integers.

Length 74 snippet

void f(register int*p,register int*q,register int l){while(l--)*p++=*q++;}

Or laid out nicely:

void f(register int *p, register int *q, register int l)
{
    while (l--)
        *p++ = *q++;
}

The keyword register provides a hint to the compiler that using hardware registers would be beneficial here. The above function will copy l integers from q to p, using hardware registers if possible.

Sometimes the speedups could be significant. For example, in the 68K microprocessor family, the line *p++ = *q++ could be translated to a single instruction MOVE.W (Ap)+,(Aq)+ vs. six or eight if you didn't use register. The 68K microprocessor had explicit post-increment and pre-decrement modes, so the savvy developer, if he knew the platform, would tailor code by using x++ and --y vs. ++x and y--.

These days compilers mostly ignore register, other than not allowing addresses to be taken of them (e.g. in the above &l would cause a compiler error).

Length 88 snippet

#include<stdio.h>
int f(int x){return(x>1)?x*f(x-1):1;}int main(){printf("%dn",f(12));}

Or with a saner layout:

#include <stdio.h>

int f(int x)
{
    return (x > 1)? x * f(x - 1): 1;
}

int main()
{
    printf("%dn", f(12));
}

Ah, recursion! The snippet is a complete program to compile, link and run. The function f calculates the factorial of its argument x by using the recursive formula f(x) = x * f(x - 1). Factorials get big really quickly, so for example f(12) is the largest value you can get in a signed 32-bit integer.

For an example of really recursive code, look into naïve implementations of the Ackermann function.

Smart compilers can optimize the function, using the hint inline and "unroll" the function when constants are provided as arguments so that:

f(12)

Becomes:

12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

Without any function calls required!

Other compilers can reorganize the function:

int f(int x)
{
    return (x < 2)? 1: f(x - 1);
}

And implement something called tail-recursion. This in effect replaces the last function call to a simple goto and lets that function deal with the return. The benefit is less stack thrashing, faster and smaller code.

In assembly language, these kinds of optimizing opportunities are really easy to spot and can be implemented by something called a "keyhole optimizer", which basically looks for small patterns and replaces them with something faster and/or smaller.

Length 117 snippet

#include<stdio.h>
int main(int c,char**v){int a,b;sscanf(v[1],"%d%*[t ,]%d",&a,&b);printf("%dt%dn",a,b);return 0;}

Or:

#include <stdio.h>

int main(int c, char **v)
{
    int a, b;

    sscanf(v[1], "%d%*[t ,]%d", &a, &b);
    printf("%dt%dn", a, b);

    return 0;
}

C borrowed from languages contemporary at the time, the concept of a universal I/O which could be consistently applied to any device, whether console, punch card, tape, disc or printer, but in true C form, it allowed the developer to create very terse but powerful statements.

In the above snippet, it will take command line input, parse two integers separated by spaces, tabs or commas and output them. It takes advantage of a newer scanf specifier %*[t ,] which will: [t ,] pull out all tabs, spaces and commas, and: * ignore them.

I remember revising some C++ code where the developer was doing everything the "pure" C++ way with << and an arsenal of methods like find and substr. It was at least a dozen lines and it still couldn't handle commas as delimiters. I replaced all that clunky code with a single sscanf line like above!

Length 132 snippet

#include<stdio.h>
int main(int c,char**v){while(--c){++v;printf("|%s|n|%5s|n|%-5s|n|%.5s|n|%5.5s|n",*v,*v,*v,*v,*v);}return 0;}

Or:

#include <stdio.h>

int main(int c, char **v)
{
    while (--c)
    {
        ++v;
        printf("|%s|n|%5s|n|%-5s|n|%.5s|n|%5.5s|n", *v, *v, *v, *v, *v);
    }

    return 0;
}

The functions printf, sprintf, fprintf etc. use format specifiers to define the width and padding of the output.

Compile and run the above using command line arguments to see the various outputs:

> main xyz 123456
|xyz|                                                                                                                                                
|  xyz|                                                                                                                                              
|xyz  |                                                                                                                                              
|xyz|                                                                                                                                                
|  xyz|                                                                                                                                 
|123456|                                                                                                                                             
|123456|                                                                                                                                             
|123456|                                                                                                                                             
|12345|                                                                                                                                              
|12345| 

Note the .5 limits the output for the specifier to at most five characters, while the leading 5 ensures the output is at least five characters, with - indicating left alignment. Combining them sets the output at exactly five characters.

Answered by user15259 on November 19, 2021

VB.net

(0 Code Example)

If you import the schema for a XML document, you'll get improved Intelli-sense support for the XML you are using. For example the rss schema.

Dim rss = XMLDocument.Load("path to rss")
Dim items = rss.<

At this point you'll see <channel>

Dim items = rss.<channel>.<

At this point you'll get

<title>
<link>
<description>
<language>
<pubDate>
<lastBuildDate>
<docs>
<generator>
<managingEditor>
<webMaster>
<item>

Let's continue.

Dim items = rss.<channel>.<item>
For Each item In items
  Dim title = item.<

At this point you'll get

<title>
<link>
<description>
<pubDate>
<guid>

Also it also works for xml node attributes. node.@


1 Char

! aka the Dictionary Lookup Literal can be used on dictionary retrieve the value of a key, the key used with the literal can not be a variable and thus changeable at runtime.


2 Chars (VB14 or later)

?. Null Propagation operator

Example usage.

Dim x As String
Dim c = x?.Length

is equivalent to the following code.

Dim x As String
Dim c As Nullable(of Integer)
If x Is Nothing Then
  c = New Nullable(Of Integer)()
Else
  c = New Nullable(of Integer)(x.Length)
End If

Answered by Adam Speight on November 19, 2021

Java


Length 44 snippet

Object a=System.out.append("Hello, World!");

Prints Hello, World! to STDOUT.

Length 43 snippet

float[][][][][]a=new float[5][3][7][2][10];

a contains 10 arrays which each contain 2 arrays which each contain 7 arrays which each contain 3 arrays which each contain 5 floats.

Length 42 snippet

interface A{static void main(String[]a){}}

A complete program. Since everything in an interface is inherently public, we can omit the word public from the main method.

Length 36 snippet

class A{class B extends A{B.B.B b;}}

A has an inner class B. This means we can declare a variable of type A.B.

But B is a subclass of A, which means it has all of the methods, fields, and inner classes of A. Thus, we can refer to the type B.B as well.

In this code, we take this a step further, and give B an instance variable of type B.B.B.

The moral: following hot questions on SO can teach you a lot of interesting, if pointless, techniques.

Length 35 snippet

l.stream().map("a"::equals).count()

If l is a list of Strings, this tells us how many of them equal "a".

Length 34 snippet

public static void main(String[]a)

Method signature of a program's main method. Just 11 more characters and we can make a complete program!

Length 33 snippet

enum D {NORTH, EAST, SOUTH, WEST}

NORTH, EAST, SOUTH, and WEST are all constants of type D.

Length 32 snippet

Files.readAllBytes("hello.txt");

Reads an entire file, returning a byte[] of the contents.

Length 31 snippet

new String(new char[]{'h','i'})

Equivalent to "hi". Useful if the " key is broken.

Length 30 snippet

new JFrame().setVisible(true);

Creates a new visible frame, which you can place other components into.

Length 29 snippet

throws ClassNotFoundException

Forces every method which call this to use a try-catch block, or else to pass the error up the stack. Checked exceptions are one of the most controversial decisions of the Java designers.

Length 28 snippet

int f(int x){return f(x-1);}

This function does not run forever; in fact, on a typical computer it takes less than a second. Thanks, Stack overflow.

Length 27 snippet

Object a=new String[]{"a"};

Creates a new array of strings.

Length 26 snippet

Object.class.newInstance()

Creates a new Object.

Length 25 snippet

((Supplier)()->-~0).get()

It's best to avoid hard-coding constants. This is an object-oriented way of getting the value 1 without using any constants other than 0.

Length 24 snippet

(Function<Long,?>)x->x+1

The successor function.

Length 23 snippet

l.removeIf(x->x%10==0);

If l is a list of integers, this removes all values divisible by 10.

Length 22 snippet

int i=(new int[7])[5];

Creates a new array of seven integers, and gets the fifth element.

Length 21 snippet

Arrays.asList(2L,"a")

Creates an ArrayList with these elements.

Length 20 snippet

System.out.print(s);

Prints s.

Length 19 snippet

import java.util.*;

Allows concise use of classes like List, Map, Scanner, Timer, and Random.

Length 18 snippet

Math.addExact(x,y)

Adds two integers x and y. If overflow occurs, the method throws an exception rather than giving an incorrect answer.

Length 17 snippet

Double.MIN_NORMAL

The smallest positive value of type double, where the leading bit of the significand is 0.

Length 16 snippet

System.in.read()

Reads a single character from the console.

Length 15 snippet

Long.reverse(x)

Reverses the bits in the binary representation of x.

Length 14 snippet

int x=050+120;

x is now 160, since anything starting with 0 is treated as octal.

Length 13 snippet

private C(){}

A private constructor prevents other classes from instantiating it. This pattern is used by the System and Math classes, among others. A private constructor can also be used to enforce the Singleton Pattern.

Length 12 snippet

static class

Allows the creation of inner classes without an enclosing outer class - a solution to a problem faced by many programmers.

Length 11 snippet

throw null;

It's often necessary to throw a NullPointerException, but it's also quite wordy. This is a much simpler alternative.

Length 10 snippet

int[]a,b[]

Defines two variables: a and b. a is of type int[] and b is of type int[][].

Length 9 snippet

switch(x)

Goes to a place, depending on the value of x.

Length 8 snippet

break a;

Breaks out of the block labeled a.

Length 7 snippet

goto x;

The goto keyword is reserved in C, C++, and Java. If x is a label, then this code sends the program to the appropriate label – in C and C++. But it Java, it triggers a mysterious RuntimeException. In fact, there is no way at all to use the goto keyword in Java.

Length 6 snippet

u003b

Ends a statement. Java is weird.

Length 5 snippet

a-=-a

Doubles a by subtracting its negation.

Length 4 snippet

a&=b

Sets the value of a to the bitwise and of a and b.

Length 3 snippet

...

Any number of arguments, consolidated into an array.

Length 2 snippet

<>

Allows the compiler to figure out what generic type you probably mean. Very un-Java-like.

Length 1 snippet

@

Indicates an annotation to allow additional information to be shown about methods and classes.

Factoid

In Java, infinite loops sometimes cause compiler errors. For example, the loop while(true); can not be terminated without exiting the method, so any code after that will trigger an "unreachable statement" error. As @Optimizer pointed out, only some infinite loops will be caught this way.

Answered by Ypnypn on November 19, 2021

TI-BASIC

[The language varies based on which calculator it is used on, but these will use the TI-84 unless otherwise noted.]

Length 31 snippet

Menu("","1",A,"2",B
Lbl A
Lbl B

This demonstrates the use of menus. The one above is quite useless, as it does nothing, but they can be used to navigate the different part of a program. The first argument is the menu title, followed by pairs of options (the string displayed followed by a 1- or 2-letter label). Here is a more intuitive example:

Menu("CHOOSE VALUE","AREA",A,"CIRCUMFERENCE",C
Lbl A
Disp πR²
Stop
Lbl C
2πR

Lbl can also be used for branching with Goto. Menus have some limitations that make them annoying to use, however: There can only be seven menu items, and each title can be at most fourteen characters, so the whole thing fits on one screen.

Length 29 snippet

Real
√(-16
a+bi
Ans
re^θi
Ans

Real (on by default) places the calculator in real number mode, so calculations involving complex numbers throw a NONREAL ANS error. When put in a+bi mode, the calculator displays answers as complex numbers if applicable, so the second example returns 4i. re^θi mode uses polar instead of rectangular coordinates, so it outputs 4e^(1.570796327i).

Length 23 snippet

If A≥9
Then
1→X
7→Y
End

This is just a simple conditional, although there can be an Else statement. Then and End are not required if it is just one statement.

Length 21 snippet

(-B+√(B²-4AC))/(2A)→X

Everyone's favorite, the quadratic formula. Stores the first solution to a quadratic equation as X, assuming a, b, and c are stored in their respective variables, as in ax2 + bx + c.

Length 20 snippet

Shade(|X/2|-3,5-X²,0

This shades the intersection of the two functions, with several optional parameters: minimum and maximum values of x and direction of and distance between the shading lines.

Length 18 snippet

LinReg(ax+b) L1,L2

Here we calculate the linear regression equation, or the linear equation that best matches a group of points, with the x-values stored as a list in L1 and the y-values in L2. There are many other regression options available, including quadratic, cubic, and exponential.

Length 17 snippet

dbd(1.2711,1.2115

This calculates the number of days between two dates, in this case January 27, 2011, the day this site started, and January 21, 2015, the day this was written. (That's 1455 days for the lazy.) The way to encode dates is a little strange: either DDMM.YY or MM.DDYY, leading zeroes optional.

Length 16 snippet

For(A,0,5
Disp A

This shows two parts of the programming side of the language. The first is your typical for loop, similar to for(var A=0;a<5;a++) in other languages. (You should also use the End command to break out of the loop.) The second is self-explanatory: it displays A, in this case 5 times because of the loop.

Length 15 snippet

Y1=|X³-4|
Y2=3X

Here are two examples of a well-known feature of graphing calculators: graphing equations. You can have 10 different equations graphed on the same plane, and there are many useful commands to find intersections, maxima, values of x, etc. Those equations look like this when graphed on a standard window:

Graph

Length 14 snippet

[[1,2][34,5]]T

The brackets are used to make matrices, and the T transposes the matrix:

[[1 34]
 [2 5]]

Length 13 snippet

dayOfWk(9,1,6

This finds the day of the week of January 6, 9 AD. The output is a number where 1 is Sunday, 2 is Monday, and so on. This particular date was a Tuesday, so the output is 3.

Length 12 snippet

Circle(1,3,5

The first of the basic drawing tools, this draws a circle on the graph with a center at (1,3) and a radius of 5.

Length 11 snippet

randInt(0,8

This generates a (pseudo-)random integer between 0 and 8 inclusive. There is an optional third argument that tells how many integers to generate. There are several other random functions, including ones for normal and binomial distributions, one for a random matrix, and one for a randomly ordered list with no repetitions. randInt can be seeded by storing a number as rand: 2→rand.

Length 10 snippet

4>5 or 2≠7

Here we have TI-BASIC's (in)equality and logic operators. The inequality statements evaluate first to 0 or 1, and or returns true if either side is true, so this displays 1.

Length 9 snippet

.656▶F◀▶D

This can convert from decimal to fraction and vice versa, which is very useful. There are also dedicated ▶Frac and ▶Dec functions that only go one way. Prints 82/125 in this case.

Length 8 snippet

lcm(14,6

This prints the least common multiple of 14 and 6, which is 42.

Length 7 snippet

getDate

Pretty self-explanatory, just prints the current system date as a list, in this case {2015 1 19}.

Length 6 snippet

√({4,9

Arrays (or lists) are surrounded by braces and separated by commas. This is similar to the map function of many languages, where it iterates through each element of the list and applies the operation outside the braces to it, in this case square root, so the result is {2 3}. Note that closing parentheses are optional, so they will be omitted from now on.

Length 5 snippet

4iii6

We've got a couple of cool things going on here. First, the real parts, 4 and 6 are multiplied, and then the imaginary parts are multiplied: i^3, or -i. These multiplied give -24i. This showcases funky-looking juxtaposition multiplication and TI-BASIC's handling of imaginary numbers.

Length 4 snippet

8°5′

This is 8 degrees, 5 arcminutes, which is converted to degrees as 8.0333...

Length 3 snippet

8→T

This shows how numbers can be stored as variables, which is somewhat unusual because the number goes first, followed by the store arrow, then the variable name. As mentioned in the factoid, θ (theta) can also be used as a variable, and variables can only be one uppercase letter.

Length 2 snippet

4M

Similarly to Mathematica, you can multiply with juxtaposition, no * necessary. All variables are initialized to 0 by default, so this will output 0 unless you have stored something else to that variable (see snippet 3).

Length 1 snippet

e

This is the constant for Euler's number, which displays as 2.718281828.

Factoid

Variables can only store certain datatypes. For example, AZ (and θ) store numerical values, str0str9 store strings, and [A][J] store matrices (2-dimensional arrays).

Answered by NinjaBearMonkey on November 19, 2021

Brainfuck

Factoid: Brainfuck (Also known as brainf*ck) was a experimental esoteric language for creating the smallest turing-complete language interpreter ever, created by Urban Müller, and is currently the most famous language of its kind. It has only eight commands, is easy to learn, but hard to use.

Brainf*ck has a tape base memory with 30000 cells and a a movable pointer, and can be visualized like this:

0 0 0 0 0 0
    ^

With the ^ character representing the pointer, and the 0's representing the values for each cell.

Brainfuck has eight instructions:

Instruction  C Equivalent              Description
+            mem[ptr]++;               Add one to the value under the cell
-            mem[ptr]--;               Subtract one from the value under the cell
>            ptr++;                    Go on cell to the right
<            ptr--;                    Go on cell to the left
,            mem[ptr] = getchar();     Read a ASCII character from input and put the result in the value under the cell
.            putchar(mem[ptr]);        Write a ASCII character to the output using the value under the cell
[            while (mem[ptr]) {        Start a while loop: Continue to matching ']' when value under the cell is 0
]            }                         End a while loop: Go back to matching '[' when value under the cell is NOT 0

Brainfuck to C:

#include <stdlib.h>

int main(void) {
    unsigned char* mem = calloc(30000, sizeof(unsigned char));
    unsigned int ptr = 0;

    // Put your brainfuck code here, converted to the matching expressions under "C equivalent"

    return 0;
}

Length 1 Snippet

Read one character and put it in the current cell.

,

Memory (with input: abc)

0 0 97 0 0 0
    ^

Length 2 Snippet

Add one to the current cell, and shift the pointer to the right.

+>

Memory

0 0 1 0 0 0
      ^

Length 3 Snippet

Remove one from the current cell until it is zero; Set the current cell to zero

[-]

Possible memory:

Memory: (Before)

0 0 100 0 0 0
    ^

Memory: (After)

0 0 0 0 0 0
    ^

Length 4 Snippet

Comments: In brainfuck, everything not a instruction is ignored. For that reason the following program is a totally valid (but empty) brainfuck program:

Hey!

Length 5 Snippet

A simple cat program (Write input to output)

,[.,]

Thanks to tomsmede for his comment

Length 6 Snippet

Move the value of the current cell to the cell to the right (Assuming the cell to the right is 0, otherwise it would add the value of the current cell to the value of cell to the right):

[>+<-]

In general, people use this code for moving a variable though.

Memory: (Before)

10 0 100 0 0 0
     ^

Memory: (After)

10 0 0 100 0 0
     ^

Length 25 Snippet

Reverse a six character input and print it, followed by every ASCII character (N-1)..1 (where N is the value of the first input character).

,>,>,>,>,>,.<.<.<.<.<[.-]

Length 53 Snippet

main(){i=0;j=0;if(i>=0){if(j<=i)i+=1;i-=1;}return 0;}

This minified C program is also a Brainfuck program in disguise, and vice versa! In fact, they (almost) do the same thing. Here's the Brainfuck code without the "comments" (C code).

><+-

Let me explain the Brainfuck code (and C code). As you can see, it uses two cells (i and j). It increments the first cell (increment i by 1). Then it decrements the same cell (decrement i by 1).

This is just a silly example of some source code being able to be compiled as two different languages and run (practically) the same.

Answered by yyny on November 19, 2021

Jot

Factoid: I can define Jot with 2 upvotes, and prove that it's Turing complete with 8 (not using lengths 4, 6, or 7).

Length 1

1

This is an example of two functions in Jot. The first is the empty string, which evaluates to the identity function. The second is 1, which is Jot's grouping operator. 1 evaluates to λxy.[F](xy) (lambda calculus notation), where [F] is the program before the 1 (here, the empty string). So, this program is the function λxy.(λz.z)(xy) which simplifies to λxy.xy.

Length 2

10

Now we are introducing the other symbol in Jot: 0. Again if [F] represents the value of the program so far, 0 evaluates to [F]SK, where S and K are from combinatory logic. I've defined the entire language now.

Length 5

11100

I will now prove that Jot is Turing complete by defining a mapping from combinatory logic to Jot. This Jot program is the K combinator.

Length 8

11111000

This is the S combinator.

Length 3

1AB

Here, A and B are not part of Jot, but rather placeholders for an arbitrary expression. The expression AB in combinatory logic maps to 1AB in Jot, with A and B recursively transformed by these three rules. QED

Length N

1
10
11
100
101
110
[...]

Every natural number, expressed in binary, is a valid Jot program. Consequently, I can algorithmically generate more snippets of arbitrary length. Given enough upvotes, I can solve the halting problem.

Answered by Phil Frost on November 19, 2021

SAS

Factoid:

SAS is a data manipulation 4th generation language dating all the way back to 1966. Despite its age, it is still widely used to this day, particularly in financial and pharmaceutical environments where a large legacy codebase has been built up over the past few decades.

Length 1

;

To the best of my knowledge, this is the only complete and valid SAS statement of length 1 - a null statement.

Length 2

x;

SAS was born out of an effort to get code from one platform working on another. It has many OS-agnostic commands for interacting with the host operating system. The x statement is one of these. A null x statement opens up a command prompt / terminal for user input.

Length 3

%a:

As well as the primary language (consisting mainly of data steps, procs and global statements), a macro language was added in SAS 5. With 3 characters, we can define a 1-letter label for use with a macro %goto statement.

Length 4

run;

Analysts typically write SAS programs in an interactive environment (the SAS Enhanced Editor window). A run statement is required in order to tell SAS to execute all the (non-macro) code that's been compiled since the last run statement. As there is often a lot of back-and-forth editing and re-running of various steps within programs, it is quite common to see a run statement at the end of every data step and proc in a program, even though most of them are probably not necessary when running the whole thing from end to end.

Length 5

quit;

Some SAS procs support multiple sequentially executed run groups and will therefore not terminate until a quit statement is issued. Others do not and will throw an error if they receive a quit statement. Still others accept only a quit statement and will throw an error if they receive a run statement. Working out which are which can be rather frustrating for new users.

Length 6

set a;

SAS data steps usually operate in an implicit loop from an initial data statement to a final run statement (or the start of another data step, global statement, or proc). Each time a set statement is executed, SAS reads the next record from the input sas dataset(s) into an area of memory known as the Program Data Vector, where individual variables can be manipulated with data step functions until the end of that iteration of the data step is reached and the record is written to the output file or dataset. This process repeats until the last record has been read from the input dataset and duly processed.

Length 7

link a;

SAS has two different versions of goto !

link and goto statements will both send you to a label elsewhere in the data step, but the difference between them is what happens when you subsequently reach a (possibly implicit) return statement. If you last came from a goto statement, you go back to the start of the implicit data step loop for a new iteration, but if you last came from a link statement, you go back to the statement just after the (most recent) link statement and continue the current iteration.

Although it stops short of explicitly advising programmers not to use these statements, the SAS help file diplomatically points out that

GO TO statements can often be replaced by DO-END and IF-THEN/ELSE programming logic.

Length 8

%let a=;

This creates/overwrites a zero-character macro variable a. It may be local or global, depending on whether the %let statement runs within a macro or in open code. It can be referred to elsewhere in the program as &a. Syntactically, this is not a special case - you never need to use quotes when defining macro variables this way, unless you want to produce a string that contains them! Also, all macro variable values are trimmed when assigned, so inserting whitespace between = and ; has no effect.

Length 9

a="""''";

In a data step, this assigns the value "'' to the variable a. SAS parses the outermost pair of double quotes first, then replaces each inner instance of two consecutive double quotes with a single double quote. The consecutive single quotes are unaffected. The converse happens if you replace the outer double quotes with single quotes.

Strange though it may seem, this functionality can actually be very useful, as it tends to be a lesser evil than using macro quoting functions. Woe betide you should you accidentally try this with an odd number of double quotes, though...

Length 10

%quote(%()

Loosely speaking, the macro processor resolves anything that looks like a macro call (i.e. with a preceding % sign) during compilation, and makes another pass during execution for anything that turns out to be a macro function or variable. Sometimes you need to mask characters that would normally be parsed as macro tokens, or which would otherwise affect compilation. This is one of the most fiddly aspects of SAS.

Depending on precisely what you want to do, SAS has about a dozen different macro quoting functions to choose from, which all behave slightly differently. %quote masks macro characters during macro execution. As demonstrated here, you can also use % characters within certain macro quoting functions to tell the macro processor not to expect a balancing quote or bracket.

Length 11

if first.a;

This is a common data step use case of by-group processing - one of the most distinctive features of SAS. When you use a by statement, SAS uses a system of input buffers to keep track of whether any of the by variables have changed value between iterations. E.g. to use the above snippet, you would need something like by a; first in your data step. Usually, this needs the dataset to be sorted in ascending order.

This snippet is equivalent to if not(first.a) then delete; which under most circumstances means if the current value of a appeared in a previous row, stop this iteration of the data step and don't output the current row.

Length 12

*";*';*);*/;

One of the joys of the SAS Enhanced Editor window - the setting in which one can run SAS code interactively - is that it is quite easy to accidentally submit an incomplete fragment of code for processing. When this happens, SAS will often appear to have stopped responding, usually because it thinks you've left a comment, bracket or quoted string open and is waiting patiently for you to close it. This snippet is an example of a 'magic string' that when submitted enough times may enable you to regain control of your session. Or not.

Length 13

data a/debug;

One largely forgotten component of SAS is the interactive data step debugger. This functions in a similar manner to the MS Office Visual Basic Editor, allowing you to execute iterations of a data step one line at a time and check the values of variables at each point. However, due to the amount of keyboard input required to operate the debugger once you've launched it, it's usually quicker just to modify your data step code so that it prints the equivalent diagnostic information directly to the SAS log.

Length 14

array a{2}(1);

In SAS, arrays are very transient things - merely a way to pick variables from a list numerically rather than by name for the duration of a data step. Once it finishes executing, the variables may still be present somewhere, but the array is gone.

When called in a data step, this snippet creates a numeric array called a containing two elements, which are auto-named a1 and a2. a1 is initialised (to 1) but a2 is not and takes the missing value ..The elements can be referred to as a[i], where i is a numeric variable or constant. Values of the array variables are retained across observations. The elements of a can be referred to as a[i], where i is a numeric variable or constant.

The second set of brackets are required to be round brackets (), but the first set can be replaced with square brackets [] or braces {}. Similarly, you can use any of these when referring to array elements in code.

Length 15

a='01jan1960'd;

We finally have enough characters to show an example of using a SAS date literal. The SAS date epoch is 1st January 1960, so this snippet is equivalent to a=0;. The core SAS language has no concept of data types beyond character and numeric, so even though we've used a date literal there's no way to distinguish between the raw output of these two statements. It's important to note that literals don't behave the same way in the macro language - if you ran something like %let a='01jan1960'd; then the resulting macro variable would be treated as a string until it was evaluated within a core language statement or function.

Length 16

where a=*"John";

Compared to some other languages, SAS has a modest set of operators (perhaps unsurprisingly, given the limited number of types). However, SAS still found space to include one for SOUNDEX matching. When included in a data step or proc, this line restricts the input to records where the variable a sounds like John - e.g. Jane would match. Unlike most other SAS operators, the sounds-like operator is only valid in where clauses, not in more general expressions.

Length 18

input a is8601dt.;

One of the strongest features of SAS is its ability to read data stored in practically any imaginable format with a relatively modest amount of code. The input statement has quite a complex syntax and can be challenging to use, but offers the greatest flexibility when reading in external data out of all the available methods in SAS.

The snippet above uses the built-in is8601dt. datetime informat to read in text of the form YYYY-MM-DDThh:mm:ss from the start of each line of an input file and store it as a numeric SAS datetime variable a. E.g. the text 2014-12-31T23:59:59 would be stored as 1735689599 - the number of seconds since 1st January 1960.

Length 19

proc means noprint;

One curious historical quirk of SAS is that it has ended up with two procs that calculate summary statistics for datasets, with near-identical features and syntax - proc means and proc summary. In early versions of SAS these were distinct procs, but over the decades they've converged to the point where they now share a help page. This example highlights one of the few remaining differences - proc means will output to the listing area by default, unless as here you tell it not to, whereas proc summary doesn't. Although this is a valid SAS statement, it is not a complete call to the proc - at a bare minimum, to request default statistics for the last used dataset, you would need to add a run; afterwards.

Length 20

data a(index=(var));

Another strength of SAS is its ability to crunch through vast volumes of data on disk, without requiring similarly vast amounts of memory - this has historically been one of the main advantages of SAS over R, though in recent years R has been catching up. As with other DBMS software, indexes help tremendously when you only need to extract a small proportion of records. This statement tells SAS to index the variable var when creating the dataset a.

When working with particularly huge datasets, normal SAS indexes can prove inadequate due to their rather generalised design - as a result, people have developed their own more specialised ones.

Length 21

%macro a(b,c=);%mend;

We now have enough characters available to define a trivial macro. In SAS a macro is simply a way of generating text, which is then interpreted as if it were non-macro code. Eventually, anyway - sometimes multiple passes are required to resolve all macro tokens.

Our macro could called like so:

%a(1,c=2);

This would create two local macro variables, with values b=1 and c=2, and then exit, generating no further code. In SAS-speak, b is a positional parameter of %a, and c is a keyword parameter. Positional parameters, when specified, must always go before keyword parameters (and in the correct order) when calling a macro, unless you refer to them by name. E.g.

%a(c=2, b=1); /*Assigns both values as expected*/
%a(c=2);      /*Sets &b to an empty string*/
%a(c=2, 1);   /*Throws an error*/

Length 22

%let a=a;%put &a.&&&a;

This is a highly circuitous method of printing the text aa to the SAS log. The initial %put &a is straightforward enough- this simply resolves &a to its value a. The . tells SAS that it has reached the end of the name of the macro variable, and is not printed. What happens with &&&a is more complex. In the first pass through the code, the macro processor resolves &a to a, its assigned value, and resolves && to &. In the second pass, the macro processor sees only &a and resolves this to a, which is then appended to the a from earlier and printed to the log. If you need to go several layers of variables in, the number of & signs required increases exponentially.

Length 23

proc datasets lib=work;

This has been described as the 'Swiss Army Knife of SAS procs', and with good reason. As well as listing, copying, appending, deleting and renaming SAS files (including, but not limited to, datasets), it can also be used to make all sorts of changes to the metadata within SAS datasets - things like variable names, formats and so on - without having to run a wasteful data step that overwrites the whole dataset. It is among the minority of procs that allow multiple run; groups (as mentioned in example 5), and requires a final quit; statement after the last one. This modest example lists the contents of the temporary work library.

Length 24

dcl hash h(dataset:'a');

Hash objects were first made available in SAS 9.1. The above statement, when run in a data step, declares and instantiates a hash object h containing variables from the dataset a. This is cheating slightly, as some additional statements are required to declare the key variable(s) you want to use to store/retrieve items in the hash, and optionally some data variables associated with each combination of keys. The most common use of hash objects is for merging small datasets onto much larger ones, as using a hash lookup to retrieve values from a small dataset avoids having to sort the other (much larger) dataset.

Length 25

proc format cntlin=a;run;

Before we had hash objects, the next best thing was a format merge. This worked by defining a custom format to translate lookup keys to lookup values, effectively resulting in the lookup dataset being loaded into memory. This snippet takes a specially structured dataset a and uses it to define one or more formats.

Format merges can outperform hash merges if you only need to look up one variable from your lookup dataset, but they have some limitations. A format can only be applied to one variable, so if your lookup depends on a combination of keys, you have to concatenate them - a messy process. Each key can then only be mapped to one value per format, so if you have multiple lookup variables you end up having to load the keys from the lookup dataset into memory multiple times - distinctly sub-optimal for larger lookup datasets.

Answered by user3490 on November 19, 2021

Pyth

For further snippets, I'll be posting solutions to golf challenges and a link to the problem.

Length 17:

<ussC,cG_GUQ*zQQ

Find the first n characters of the infinite sequence formed by repeating the input string forever, then filling in its underscores with the sequence itself, then repeating that forever.

Fill In the Blanks

Length 14:

#QX=Qhf>FT.:Q2

Given a list of unique elements, sort the list by swapping pairs of neighboring elements, printing out all intermediate results.

Rearranging a set of numbers into order

Length 13:

?hu]+HG_UQYQY

Create the following structure: [0, [1, [2, [3]]]].

Home on the Range of Lists

Length 12:

uxyG*HQjvz2Z

XOR multiplication.

XOR multiplication

Length 11:

lfqSzST.:wz

Count how many substrings of the first word are anagrams of the second word.

Detecting anagrams within a Parent String

Length 9:

fqJjQT_J2

Find the lowest base in which the input is a palindrome.

Lowest-Base Palindrome

Length 5:

!%lQ1

Check whether the input is a power of 2. Take the log base 2, take the result mod 1, and take the logical not.

Check whether an integer is a power of 2 without using +,- operations

Length 4:

sjQ2

Calculates the hamming weight of the input by adding up the base 2 representation of the input.

Count the number of ones in unsigned 16 bit integer

Length 3:

^G2

^ on sequence, int, gives the cartesian product of the first argument with itself n times, where n is the second argument.

In this case, since G is the alphabet (abcdefghijklmnopqrstuvwxyz), ^G2 gives all 2 letter strings, aa through zz.

Length 2:

lT

l, while normaly serving as len(), can also be used as log base 2. Since T is the variable initialized to 10, this prints 3.3219280948873626, log base 2 of 10.

Length 1:

H

H is the empty dictionary (hash-table) in Pyth, and is the only way to get a dictionary in Pyth, short of using v (eval) or $ (Python literal).

Factoid:

Pyth has no multi-character constructs other than literals. Also, Pyth compiles essentially one-to-one into Python.

Answered by isaacg on November 19, 2021

Marbelous

Length 14 snippet

}0}1
Mulx
HxHx

This snippet shows off some more of Marbelous libraries and introduces a new concept, namely, multi-cell boards. The Mulx board takes two marbles as input and outputs 2 marbles. Marbles that enter the leftmost cell of the Mulx will correspond to the }0 devices in that board and the rightmost cell to }1. Analogously, the outputs will come out of different cells as well. The width of a board can be calculated as MAX(1, highest output device + 1, highest input device + 1) cells that don't correspond to an input device will trash any marble that falls upon them.

Length 13 snippet

7E
??
>Y!!
{0

This is a board that will spit out a random printable ascii character on each tick. Marbelous has two ways of generating random values. There is ?? which returns a random value between 0 and the input marble it receives, inclusive, and ?n: ?0 up to ?Z respectively. Which act very similar to ??. We also have !! which terminates the board even if not all outputs are filled. Can you figure out how the ?n devices could be implemented as boards in Marbelous using ???

Length 12 snippet

}0}1
Fb//
Dp

Here we see a few library functions of Marbelous in action. Fb outputs the nth fibonacci number where n is the input marble. Dp prints the input marble to STDOUT as a decimal number. These are both implemented in Marbelous and can be called upon when you check include libraries in the online interpreter, for the python interpreter, you have to explicitely include each file. The inplementation of these boards can be found on github. Note that this particular program takes 2 inputs and will call the Fibonacci board two times. Boards that are called are return within one tick of the board that called them.

Length 11 snippet

}0}0
{<{0{>

This one needs some explanation. The }0 devices are imputs, since they have the same number (0), they will contain the same value when this board gets called. The three devices on the lower row are outputs. {< outputs to the left of the board, {0 outputs underneath the first cell of the board and {> outputs to the right. Output is only pushed when all distinct output devices are filled. In this case however, the right output device is never reached. The board will exit because of lack of activity and output the two values it has anyway. Can you imagine how one could implement / as a Marbelous board?

Length 10 snippet

..40
FF
\

There's a few things that play an important role in Marbelous here. Firstly, there's addition. If you trace the path of the two marbles on the board, you'll notice that they'll end up on the same cell at the same time. When this happens, they'll be added together. (fun fact: at some point it was considered that instead of being added together, the marbles should form a stack) However, Marbelous is an 8 bit language, So adding a marble to FF is equivalent to subtracting 1 from it.

Length 9 snippet

00
\/]]

This is the shortest way to implement a rudimentary version of cat in Marbelous. 00 / Is a loop that puts a 00value marble on the ]] device every second tick. This is an STDIN device. When a marble lands on this device, it tries to read the first character from STDIN, if there is one, it gets pushed down (and in this case printed again). If there isn't one, The original amrble gets pushed to the right. (and in this case trashed)

Length 8 snippet

}0
~~
{0

This snippet shows a few features. Firstly it takes input through }0. In this case this is the Main Board and this will be replaced by the command line input. You can also call this function, in that case, the argument will be taken instead of the command line input. Then there's ~~, which is a bitwise not operator. After that, we get to }0, If all }n devices are filled, these values are returned as the functions return values. (Marbelous supports more than one return value per function)

Length 7 snippet

00
\/

This is the most compact infinite loop you can create in Marbelous. The \ device pushes any marble to the right, / copies a marble and pushes one copy to the left and another to the right. Since the board is only two cells wide, the marble to the right gets trashed though.

Length 6 snippet

46MB75

Here's an example of recursion, MB (the implicitly named main board gets called on every tick, but not before Printing Fu to STDOUT on each call. (Resulting in the following: FuFuFuFuFuFu... This obviously overflows the callstack.

Length 5 snippet

2A
++

Some arithmetic, The marble with value 2A falls down on teh first tick and the finds itself on the ++ cell. This is an operator. This particular operator increments any marble that land on it and lets it fall down. The marble now has value 2B and falls off the board. This prints + to STDOUT.

Length 4 snippet

:
24

The two interpreters disagree here, I've given the first board of the file a name in this example (The name is an empty string). The python interpreter assumes this is the Main board and calls this board upon running the program (which prints $). The javascript interpreter doesn't find the Main Board and thus no entry point. This can be useful when writing a library file for Marbelous.

Length 3 snippet

:Bo

This is a named board, with no body, we can call this board by Writing Bo in a cell of any board (including Bo itself)

Length 2 snippet

3A

This code is the body of a 1x1 cell (each cell is two characters wide) board, implicitly named MB (for Main Board). It prints the ascii value of the hexadecimal value of 3A when the marble falls off the board. The output of this program just so happens to be the source code of:

Length 1 snippet

:

Along with #, this is one of the two the only valid 1 character programs in marbelous. # is an indicator of a comment an therefor not very interesting. : tells marbelous that you're about to declare a board. Neither of teh two compilers care that you don't actually name or define the board. The program doesn't do anything.

factoid:

Marbelous was developed by people on this site, some names that were in the running for this language were Rube and simply Marbles.

Answered by overactor on November 19, 2021

><> (Fish)

(Note: Some snippets build on previous snippets, so unlike most answers I've decided to put them from earliest to latest.)

Factoid:

Like Befunge, ><> is a stack-based 2D language. This means that instructions aren't executed linearly like most traditional languages — program flow can be up, down, left or right!

Length 1 snippet:

X

X is an invalid command in ><>, so the error message something smells fishy... is printed. In fact, this is the only error message in ><>, whether the cause be division by zero or trying to pop an empty stack.

Length 2 snippet:

1n

Program flow in ><> starts from the top left and is initially rightward. 1 pushes a 1 onto the stack, then n prints it as a number (as opposed to as an ASCII char). But ><> programs are toroidal, meaning that the instruction pointer wraps around when it reaches the end of a line. So after the n we wrap to beginning, push a 1, print, wrap to the beginning, push a 1, print ... and we end up printing 1s forever!

Length 3 snippet:

"o;

Here " is string parsing, o outputs as an ASCII char and ; terminates the program. But what does the program actually do as a whole?

Well first we start string parsing, pushing every char we see onto the stack until we find a closing ". We push an o, then a ; ... and wrap the instruction pointer back to the start. But now we're on a " so we stop string parsing, and finally we execute the o and ; as normal to print the top of the stack (the ;) and terminate.

Yes, we've just used the same quote char to start and end a string!

Length 4 snippet:

42n;

Based on what we've seen so far, you might expect this to push 42, output as a number then terminate. But all instructions in ><> are single chars, so this actually pushes a 4 and a 2, then outputs the top of the stack as a number (only the 2) and terminates.

Length 5 snippet:

<v
;>

Remember, ><> is a 2D language. This means that there's got to be ways to change the direction of program flow!

Like Befunge, one way you can do this is via the arrows >^v<. To illustrate how they work, let's look at the above program:

  • Program flow is initially rightward
  • < makes program flow leftward — we go off the left and wrap around to the v
  • v makes program flow downward — we go down to the >
  • > makes program flow rightward — we go off the right and wrap around to the ;
  • Finally, we terminate.

Length 6 snippet:

";"00p

Another cool feature of ><> is that it's reflexive — the program can modify its own source code on the fly!

Here we push a ;, followed by two zeroes. p then pops the top three elements y, x, v (y being the top of the stack) and places v at the position x,y. In other words, the p in this program puts a semicolon at the position 0,0, turning the code into ;;"00p. This then allows the program to terminate, as the instruction pointer now wraps around and executes the newly-placed ;.

Length 7 snippet:

7*n;
6

Unlike Befunge, ><> also has mirrors (/|_#) which reflect the direction of program flow. So here we:

  • Start rightward, but the reflects us downward
  • Push a 6 and wrap
  • Hit the backside of the and reflect back to rightward
  • Push a 7
  • Multiply the top two of the stack
  • Output and terminate

Moving horizontally through a _ mirror or vertically through a | mirror is a no-op.

Length 8 snippet:

"r00g>o<

Quite possibly the simplest ><> quine if an error is allowed to be thrown. The two new instructions here are:

  • r: Reverse the stack
  • g: Get — pop y,x and push the character at x,y onto the stack (counterpart to p)

Using the string wrapping trick from before, the program initially pushes r00g>o< then hits the first quote again. The stack is then reversed, giving <o>g00r. After that we push the char at 0,0, the ", to give <o>g00r". Finally, we trap an o between two arrows, outputting the top of the stack until there's nothing left and we get an error.

Length 9 snippet:

x0>
1n>

x (lower case) moves the instruction pointer in a random direction, and the program showcases this functionality by printing random bits forever. Try following the arrows and mirrors to figure out how this works! (Don't forget to check all four directions, including up and left)

Length 10 snippet:

;a comment

There's no comment syntax in ><> — it doesn't need one. Just write what you want anywhere and make sure it doesn't get executed as code!

Length 11 snippet:

1!X2!X+!Xn;

! is a trampoline which skips over instructions. It's particularly useful when used with ?, a conditional trampoline which pops the top of the stack and executes the next instruction if the popped element is nonzero. We'll see how this works later.

The above code prints 3 by skipping over the Xs, only executing 1! 2! +! n;.

Length 12 snippet:

01v
ao>:@+:n

Prints the Fibonacci numbers forever starting from the second 1, one on each line. The new commands are:

  • a: Push 10, which we need for newline. a-f push 10 to 15 respectively.
  • :: Duplicate top of stack
  • @: Rotate the top three elements of the stack, e.g. [5 4 3 2 1] -> [5 4 1 3 2].

Trace for the first few iterations:

enter image description here

Length 13 snippet:

i:d=?v
l?!;o>

A "tac" program which reads in a line of input and outputs it reversed. Thanks to @tomsmeding for the snippet.

= pops the top two elements and pushes 1 if they're equal, 0 otherwise. The first line keeps reading in input until ASCII char 13 (carriage return) is found, at which point it moves to the second line.

The l?!;o loop is an important construct in ><> which outputs the entire stack. Unlike >o<, it doesn't cause any errors. This is how it works:

  • l pushes the length of the stack
  • We check the length with ?:
    • If the length was nonzero, then the next instruction ! is executed, skipping the ;
    • If the length was zero, then we don't execute ! and terminate due to the ;

Note that no output actually happens until you hit carriage return.

Length 14 snippet:

32.

   X67*n;

In addition to changing the direction of program flow, you can actually move the instruction pointer anywhere you like!

. pops y,x and teleports the instruction pointer to x,y, maintaining direction. Note, however, that you need to move to one square before where you want to go — the instruction pointer is updated before the next instruction is executed. So here the instruction pointer lands on the invalid X, but all is okay since the pointer moves to the 6 before continuing execution.

. makes it possible to convert most ><> programs into a one-liner, but why would you want to lose the fun of 2D? :)

Length 15 snippet:

01+:aa*=?;:nao!

Prints the numbers 0 to 99, one on each line. This program demonstrates a neat use of the ! trampoline — to ensure that the initial 0 is only pushed once.

Length 16 snippet:

"r00g!;oooooooo|

A proper quine which doesn't throw errors, inspired by the quine on the esolang page.

If you wondered about how to modify the previous quine (snippet #8) so that it wouldn't cause an error and thought "why don't I just add a ton of o instructions?", then you might realise that for every o you add, you need to output another o! This quine neatly solves the problem by putting a | mirror at the end, which allows each o to be used twice.

If we switch to single quotes (which are also for string parsing), then an alternative quine which doesn't use g is

'r3d*!;oooooooo|

Length 17 snippet:

b2,63,.

   17,n;

We have addition (+), subtraction (-), multiplication (*), modulo (%)... but what about division? It's there, but since / is already a mirror, division has been assigned the , symbol instead. Interestingly, division is float division, not integer division!

The above program explores some undefined behaviour by trying to jump to 11/2, 6/3. The Python intepreter seems okay if the first coordinate is not an integer (although it jumps to the wrong spot), but chokes if the second isn't.

Length 18 snippet:

123456${{$}nnnnnn;

We've seen r which reverses the stack and @ which rotates the top three elements. Here are a few more commands which move elements on the stack:

  • $: Swap the top two elements
  • {: Shift the whole stack left
  • }: Shift the whole stack right

To show how this works, here's the program trace:

123456 ------> 123465 ------> 234651 ------> 346512 ------> 346521 ------> 134652
       $ Swap        { L shift      { L shift       $ Swap        } R shift

Then we output, giving 256431.

Length 19 snippet:

"reward"4[roooo]oo;

Up until now I've been saying "the stack", "the stack"...

Although most programs use only one stack, ><> can actually have multiple stacks! Here are the relevant instructions:

  • [: Pops x and moves the top x elements to a new stack
  • ]: Removes the current stack, and moves its values to the underlying stack.

Here's the trace for the above program:

       [r e w a r d]       Push "reward"
4[     [r e] [w a r d]     Move four elements to a new stack
r      [r e] [d r a w]     Reverse the current stack
oooo   [r e] []            Output "ward"
]      [r e]               Remove the current stack, no values to move
oo     []                  Output "er", giving "warder" altogether

Note that simply pushing reward and then outputting it again with oooooo would print drawer, due to the "first in, last out" nature of stacks.

Length 20 snippet:

aa*5+
7a*2+
oo;  

A little known feature of ><> is that, like Python, backslashes can be used for line continuation in many cases.*

The above code is functionally the same as

aa*5+7a*2+oo;

*Disclaimer: The reason why this works may or may not be for a completely different reason

Length 22 snippet:

1&fv ;n&<
&1->:0=?^:&*

In addition to stacks, ><> also has registers (one for each stack) which can be used to store values. Calling & for the first time moves the top value of the stack to the register, and executing & again moves the value back. This can be very useful when accumulating a value, for example sums and factorials.

The program above calculates the factorial of f (15), printing 1307674368000. Here's the trace for f replaced with 4:

enter image description here

Length 24 snippet:

"Hello, World!"rl?!;of0.

We have enough chars for everybody's favourite program! Here we use the . teleporter for the output loop.

Length 25 snippet:

0i:0(?v$a*$"0"-+!
   ;n~<

Unfortunately ><> only allows reading from STDIN one char at a time, which makes reading in numbers a little tricky. For input consisting of digits 0-9, this program is essentially atoi, converting a string of digits from STDIN into a number on the stack (which is then printed).

Another note is that on EOF, i pushes -1 onto the stack. This makes checking for EOF easy by comparing to 0 using (, or "less than".

This snippet also uses ~, which pops and discards the top element of the stack.

Length 33 snippet:

i>:nao:1=?;
 ^  ,2v?%2:/
 ^+1*3<

Up until now, most snippets have either been relatively linear, or were just simple examples demonstrating ><>'s functionality. Now I can give an example which highlights how easy it is to visualise program flow in ><> with a well-laid-out program.

The program reads in a single ASCII character and runs the 3x+1 algorithm on its code point (In ><>, characters are basically integers). Each step of the algorithm is printed until we hit 1.

Here is a trace for the first few iterations with input a (code point 97):

enter image description here

Length 44 snippet:

a&>i:0(?v"+"$
/&^?=0l< "a*"/
:1+&2p/
n
;

I don't feel like I've done the p command justice, having only used it once all the way back in snippet #6, so here's a different atoi function. What's cool about this one? The program writes the expression needed to calculate the number as it reads the input!

So for input like 573, after all chars are read the end of the third line will look like a*5+a*7+a*3+, which evaluates to 573!

Once again, the input is expected to be digits only. Trace GIF here.

Length 74 snippet:

>i:'A'(?v:'N'(?v:'['(?v
  :'a'(?v:'n'(?v:'{'(?v
^      o<    +d<  -d-d<o

If you've managed to get down to here, then you might agree with me when I say that this is one very readable ROT13 program. Given a char c1, we find the first char c2 in AN[an{, such that c1 < c2, then apply the appropriate offset by adding/subtracting d (13). Note that [ and { are the chars directly after Z and z respectively.

Try it in the console, and watch the letters transform as you type!

(You can also pipe in the input, but as I'm missing the EOF check :0(?; it'll stop with an error when it tries to print -1 as a char)

Answered by Sp3000 on November 19, 2021

CJam

Try the below snippets here

Length 20 snippet:

q~{]__~zz<=~*0>*}*

A min-mod calculator. An excerpt from the question :

The minmod function is a variant of the familiar min, which appears in slope-limiting high-resolution schemes for partial differential equations. Given a number of slopes, it picks out the flattest slope, while taking care of relative signs between the slopes.

The function takes an arbitrary number of parameters. Then minmod(x1, x2, ..., xn) is defined as:

  • min(x1, x2, ..., xn), if all xi are strictly positive
  • max(x1, x2, ..., xn), if all xi are strictly negative
  • 0, otherwise.

Length 18 snippet:

l'[,65>Dm>_el+_$er

A ROT13 encoder. Shifts only a-zA-Z characters from the input string via STDIN

Length 15 snippet:

T1{_2$+}ri2-*]p

A full program to print the first N numbers from a Fibonacci series where N is provided as an input via STDIN.

Length 12 snippet:

{{_@%}h;}:G

A simple GCD function. This can be used like 2706 410 G to get the GCD on stack.

Length 11 snippet:

123456 789#

# is the power operator. This snippet shows a cool feature of CJam that it supports BigInts for almost all mathematical operations. So the output of the above code is

1596346205622537943703716803040694151242100030904924074732295184521676912291137885341977590649991707684635184329980991487148618486236239062505001539322685142817506810040361209550544146292158784625519911512640361780862459268161619223326802388689703997604303632605734938879647069477372395799326590488746599202521617640394227957532720581758771344616555153473551874187964029973716015080326283503474062024803237072761129557356772954771383125420283743787215768524095651476398918270831514362626616089349128838080859262141293069421199363839940462244772673481244848208112002212957221705577938865719802035511067875502253218277834350725436729497351901219311577128600087062378434520948898301738545267825952998284599001356281260973911216650526574435975050678439968995805415462116669892745933523276658479456263859786003695570642598885206779863730608803831608206418317758451327165760242416052588688579435998154295782751455020445483571514197850814391880423853968520336337963918534259580183058727377932419280412466915889059399591196961188841001024998633317094826403760131868252088477018937989608302521450181593409274231460335072324865982559395114735391976545471553525054490202974741119144469523879456646833238659929705233941114530149037245274032070536718197592615630616792756562341411027203615235147973615347081993563361626845258162606172599728677944001956482301240050182368840648532697569098833480384074404562991348377266778603059081932412368912313845464302833428950934701568958836851009236647605585910687215977468114323293396641238344799575626940766355697576957869656153567798618227770961980620119004224798449940378878601283741944503399682599666873704888519152796472231721010884561046439019823540214190109829183178504573391524533915085342799888899681052113605127068137552531204917650779012455136663716975904242872042805633443567570913936237754642040107392687168596924804730637819953463737212774674563401663682370631910559669378413063684132477269578881395521544729393136204246705936061735379354437327940116154383441927197123218522827575163913310005036963663583344508839784971260123709283218409462028161021477446586507813599051643059982983426688872855309396405653159417356549291603532443699350168178837164682957610433456205211423600319694496115159970718912091395232327389520091646132878609779171226748990343349416763319432268713023302555895744813731889452605219001900815755497209921418814092923394321459962373890912709775151652200071533644718727513889263907829300496554849544461628702471995210369421320165755673222520834013956492183306187393652197405863508709529644837118590847002900783148394313160749018413291215958936871830666201928218294362550829287373305552379418641499562597137520153409556227576809855521876196531587454478159211299517511047868125975115347272184123454929507976958328038242400918390689757262398695703472270927183494613959476164389143107240083171566284628032072645081703351075328092783401422849512230275075331561337345714881104575020436358133210849231625973013523497330004645467493618279226202227586584610761439335895760888873155403816627190368675397978355381544497413492223577022267403347927237298551052219150516984577176643706356698282552857754120841266435149587248192704898338826251727748499150285409036076919533685800933215325289882260771526293167171975367192287689881199864600661035143522211647660445960687046757311913589429739868592726372013684511683081229044622752191694278221303073075505531920922815724661725685493922212700535444400760813940151761980008355835574184921854364539924999643954874549857103642483664109073938527328920827803218865362851320233433429604394590974694396314165313743853607609394553133883545319222169958204731303672940856293527174545435349105954532301106962634516087237739490953930886293289854731305112253177512851251930821765454042415085420000484369355605183062368648992392499663861508991984554431113080399485470268940148600970493633737364443822752829774334511729579419931500217970224646496435527826186627011323464848141074486509849545954714213290443775688291020289759390171236344528896

Length 10 snippet:

"`%W_"_W%`

We've already done quine, lets reverse it!. This is one of the shortest reverse quine in CJam. Reverse quine is a quine which prints its sources code in reverse order.

Length 9 snippet:

5,K,+_&S*

This snippet showcases a lot of features of CJam,

5, "create an array of numbers 0 to 4"
K, "create an array of numbers 0 to 19"
+  "List concatination"
_  "Duplicate top stack element"
&  "Set distinct operator in this case"
S* "Join array elements with space character"

Length 8 snippet:

"`_~"`_~

One of the smallest possible quines in CJam. This is a true quine in a sense that it does not actually read the source code in any manner. (Reading the source code is not even possible in CJam)

Length 7 snippet:

"AB"_m*

m* creates all the Cartesian products of the top two stack elements. For instance, the above code will put ["AA" "AB" "BA" "BB"] on stack, which is the cartesian product of "AB" and "AB".

Length 6 snippet:

"_~"_~

A nice looking repeated code. DO NOT run this :) . This representation of code is the basis for the simplest quine in CJam. You put string "_~" on stack, make a copy (_) and evaluate it. Which in turns does the same thing again (and again ..) until you reach maximum recursion exception.

Length 5 snippet:

{A}:F

This is how a basic function works in CJam, The above expression assigns the code block {A} to variable F. Now in your code, you can put F anywhere to run the code block (and get 10 in this case)

Length 4 snippet:

"A"~

You can evaluate any code block or string or even a single character using ~. The above expression results to 10

Length 3 snippet:

Kmr

A typical random number generator from range 0 to K i.e. 20.

Length 2 snippet:

es

This gives the current timestamp (milliseconds from the epoch). CJam also has et for local time in a more usable format which returns an array comprising of the various parts of the current time ( day, hour etc).

Length 1 snippet:

A

CJam has almost all capital alphabets as predefined variables. A is 10, B is 11 and till K is 20. P is pi (3.141592653589793), N is new line and many others. These can come very handy when you need initial values in variables, or even when you need two digit number in 1 byte.

Factoid

CJam is inspired by GolfScript but builds a lot of features on top of it including support for a network GET call :D

PS: I will try to update the answer every 5 upvotes or every 2 hours (which ever is earlier)

Answered by Optimizer on November 19, 2021

J

PS: Snippets now linked to tryJ.tk letting you play around with them running in JavaScript in your browser, without installing J.

PPS: I swapped order; this makes more sense for people joining in, and for future reference.

PPS: I think, due to time constraints, I will add one snippet a day

factoid:

J is a descendant of APL (see here for the family history) minus the funny character set.

Length 1 snippet

_

J uses _ both as infinity and as negative indicator, when attached to number literals (opposed to the verb -).

Length 2 snippet

a.

a. is called Alphabet, containing all 1 byte characters. As such J does not contain functions like atoi, since they are simple look-ups in the alphabet: a. i. 'z' =122

Length 3 snippet

i.9

i. is for Integers, when used monadically (ie. only one argument, the right one, usually called y). When used dyadically it serves as index of, as in the example above.

Length 4 snippet

!!6x

J supports arbitrary precision integer and rational numbers. This calculates the factorial of the factorial of 6 (a 1747 digit number).

Length 5 snippet

^.^:_ 

A dense one... First, verbs (as J calls functions) are organized by theme. All ^ verbs are tied to exponentiation. ^ for exponentiation (and exp when used monadically, ^. for logarithms. ^: is a special one, the Power conjunction (a higher order function), which applies a function a number of times. When right the argument is infinity (_) it executes its left argument (in the example ^.) on its own output till it converges. In effect, ^.^:_ is a verb solving x = ln(x) when applied to any argument but 1, yielding 0.318132j1.33724.

Length 6 snippet

^0j1p1

or equivalently

^o.0j1

Euler's Identity in J. As cited above, ^ is exp(). Apart from arbitrary precision integers and rationals, it also supports powers of pi and complex numbers, and combinations hereof as literals. 0j1p1 means (0 + j) * pi ^ 1.

Length 7 snippet

+/&.:*:

A verb taking the 2-norm of any vector. This demonstrates 2 things:

  • the Insert adverb turns the Add verb + into Sum by inserting it between each element of its argument. Hence (0+1+2+3) = +/ i.4 .

  • The conjunction Under when used as v &.: u y is equivalent to vi u v y, where vi is the obverse (generally the inverse).

Yes, J knows about functional inverses. Combining these makes the verb in the snippet equivalent to %: @: (+/) @: *:, or sqrt(sum(y.^2)) in Matlab for instance.

Length 8 snippet

$#:I.@:,

A fork is composed of 3 verbs without any reference to arguments. This allows what in J is called tacit (point-free) programming. A fork f g h, in the monadic case (as in this example) is equivalent to (f y) g (h y). As forks, multidimensional arrays are an intrinsic part of J. "Indices" returns the indices of ones in a vector, but does not extend to higher dimensions as such. This example uses Shape, Antibase and I.@:, as the 3 tines of the fork implementing I. for higher dimensional arrays, for instance:

 ($#:I.@:,) 5 = i. 5 5 NB. indices of 5 in i. 5 5

Length 9 snippet

<"1 i.4 6 

Boxed arrays are a data type in J, allowing to combine heterogeneous content (both type and size) into one value. Monadic < boxes it's argument. Rank is a central concept in J, and allows to automatically extend verbs towards arrays of higher dimensions. Both nouns and verbs have a rank.

Noun rank is the number of dimensions of any noun, which the verb $@$ can tell you. For example i. 2 3 4 is an array of rank 3.

Verb rank is the rank onto which a verb will apply itself. Every verb has an intrinsic rank which can be queried with the Basic conjunction. v b. 0 returns 3 numbers for the monadic, dyadic left and dyadic right rank of the verb v.

A verb works on noun cells of rank equal to the verb rank, and replaces results in a noun rank-verb rank frame. A verb's rank can be limited using the Rank conjunction, as is done here, boxing rank 1 cells (rows) instead of working on rank _, ie. boxing the entire array. More info on rank can be found here.

Length 10 snippet

<./ .+~^:_

This snippet is a verb calculating the shortest path over weighted digraph. It introduces minimum (<./) and the Dot conjunction. The dot conjunction is a generalization of the matrix product, which can be written as +/ . * . Generally, u . v is equivalent to u@(v"(1+lv,_)) where lv is the left rank of the verb v. Or in words "u is applied to the result of v on lists of “left argument cells” and the right argument in toto". (See above for ranks)

As such the inner verb <./ .+~ replaces item y(i,j) with the minimum of y(i,k)+y(k,j) for all k.

^:_ iterates this step till convergence.

Example, displaying original and shortest path distances:

(]; <./ .+~^:_ ) wtm=: _6] 2 5 _ _ _ _ 0 4 1 3 _ _ _ 0 _ _2 _ _ _ 4 0 _ 5 _ _ _ _1 0 6 _ _ _ _ _ 0

Length 11 snippet

<[email protected]^99

This snippet introduces special code: Some J code is supported by code specifically written for a certain use case, recognized at parse time, and optimized; either for higher accuracy (as is the case here) or higher performance (see Special combinations)

This phrase gives 99 digits of pi (though shifted 99 decimal places). Special code depends on exact phrasing, what would normally be equivalent is not as precise as the snippet code: <.o.10x^99 looses the extended precision.

Length 12 snippet

($-.1:)($,)]

From time to time, you end up in situations where due to selections made in data, there are singleton dimensions running in the way. This handy utility, called squeeze in Matlab, squeezes out all singleton dimensions. The left tine of the fork ($-.1:) yields all dimensions without the ones, while the middle one ($,) reshapes the raveled array to the dimensions retained. The right tine ] serves just to make this a fork, and references the right argument.

Length 13 snippet

1 :'-u%u d.1'

Newton's Method finds an approximation of a root of a differentiable function. This explicit adverb is to be applied to the function of which the root is sought, and represents one step of the iterative procedure. u is the argument referencing the function, being replaced the moment the adverb is applied. d. is a conjunction deriving functions symbolically, and might here be replaced by D. which does the same numerically (but differs when applied to higher rank functions). The result is a hook subtracting the fork ( u divided by its derivative) from the argument.

For example:

(_2 + *:) (1 :'-u%u d. 1')^:_ ] 1 NB. root of x^2-1; ] is there to avoid combining _ and 1 into an array.

Length 14 snippet

(%-.-*:)t.i.10

First 10 numbers of the Fibonacci series by Taylor expansion of x / (1 - x - x^2). Analyzing the hook %-.-*: gives (y % (-.-*:) y) = (y % ( (1 - y) - *: y).

Length 15 snippet

(#{.+//.)!/~i.9

Another take on Fibonacci series. This time from another angle; starting from Pascale's triangle '!/~i.9' .

/ when used dyadically means Table, applying the verb it's bound to between each cell of it's arguments, yielding a table of the operation between arguments x and y. In this case ! used dyadically, as Combination (or Out of). ~ makes the verb Reflexive, ie. use it's right argument as the left one too.

The adverb /. is an odd one, it applies it's verb along the anti-diagonals of an array (ie. try </.!/~i.5 here )

So this snippet takes the sums on the 9 first anti-diagonals on the Pascal's triangle, which happens to be another occurrence Fibonacci series.

Length 16 snippet

;/@~.,. <"0@#/.~:

Ok, I added a space just to get to 16 :). This snippet demonstrates a fork using Key: listing all items in the argument and their frequencies.

x u/. y applies u to y in chunks where x is unique, or in J : (=x) u@# y, where = is Self-Classify, which generates a boolean array containing 1's in positions where they appear in the nub ~. Here it's applied reflexively, hence executing Tally on each unique item in y, counting the number of appearances.

As most verbs in J keep the nub order (order of appearance of new unique items, opposed to for instance unique in Matlab, which sorts its argument) this can be used for Stiching the items to their frequencies as is done here. ;/@~. is used to make a boxed list of all items.

Note that because the prevasive concept of Rank, this code works for any dimensionality.

Length 17 snippet

*./ @:(#&>)@C.@A.

J supports a few primitives specifically about permutations:

  • Anagram A. Monadically it finds the Anagram index, dyadically, it applies the permutation specified by the anagram index in the left argument to the right argument.
  • Cycle - Permute C. converts between direct and cycle representation of permutations.

This snippet is a verb that takes an anagram index to the left (between 0 and !#y) and right argument y an array to permute. Afterwards, it computes the LCM *./ of the cycle lengths #&>, ie. the period after which you get the original array back:

]n=: (p=:?!9) *./ @:(#&>)@C.@A. i.9 NB. period of a random permutation
p&A.^:n i.9 NB. applies permutation n times.

Length 21

<:@(#/.~)@(i.@#@[,I.)

This little verb comes from the "stats/base" add-on, and is called histogram. It does exactly that, given a list of bin starts, sums all occurrences of data between in the interval ]bn-1,bn] where bn is the start of bin number n.

It exploits Interval Index I. for finding the interval of:

If y has the shape of an item of x , then x I. y is the least non-negative j such that j{x follows y in the ordering, or #x if y follows {:x in the ordering or if x has no items.

Making the totals of each interval is done using key as highlighted in snippet 16.

The snippet linked to on tryj.tk demonstrates the central limit theorem using this histogram:

(bins=:(%~>:@i.)10) ( [ (graph=:(,&":"0 1 '#'#"0 1~])) (histogram=:<:@(#/.~)@(i.@#@[,I.)) ) (+/%#) ?5 200 $ 0

Length 22

=,&(+/)(~:#[)e.&~.~:#]

Fun in J. This implements a mastermind engine, taking a secret array as left argument, and a guess as the right. The values returned are the number of white and black pegs. Taken apart:

NB.   ExactMatch: checks where digits correspond:
ExactMatch =: =

NB.   GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right
NB.   pairs of parentheses, and checks them for same elements(e.), after eliminating
NB.   doubles in both (&~.)
GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ])

NB.   Piecing the conditions together, after summing the booleans:
mm =: ExactMatch ,&(+/) GoodDigitWrongPlace

To be used like

secret (=,&(+/)(~:#[)e.&~.~:#]) guess

Where secret and guess are any array. It works with any data type actually.

Answered by jpjacobs on November 19, 2021

Mathematica

You might want to read this bottom-to-top since that's the order it was written in, and some explanations will refer to previous snippets or assume explanations from further down.

The list is growing quite long. I've started to remove less interesting snippets, and I will start skipping snippets now. See the revision history for a complete list of snippets up to 41. For some real gems, check out snippets 81, 64, 44, 23, 19, 12 and 8.

Length 143 and 144 snippets

Finally... I've been waiting for this for a while (and been golfing it for about as long, so I don't have to wait even longer). I mentioned earlier that you can also equations numerically, and that you can also solve differential equations. I wanted to show a non-trivial example of that.

Consider a double pendulum on a rod (i.e. a pendulum attached to another). Each rod has unit length and each of the two pendulum weights has unit mass. I've also used unit gravity to shorten the equation. The following 143-character snippet solves the Lagrangian equations of motion for such a system (in terms of the pendulums' angles and angular momenta). A derivation can be found in this PDF, although it's a fairly straight-forward exercise if you're familiar with Lagrangian mechanics.

It's quite unreadable, because I had to golf it down a lot:

d=θ@t-φ@t;NDSolve[{#''@t==-#4#2''[t]Cos@d-##3#2'@t^2Sin@d-Sin@#@t&@@@{{θ,φ,1,.5},{φ,θ,-1,1}},θ@0==2,φ@0==1,θ'@t==φ'@t==0/.t->0},{θ,φ},{t,0,60}]

What's neat is that Mathematica immediately displays a miniature plot of what the solutions roughly look like:

enter image description here

Okay, but that's a bit lame. We want to know what the motion of the pendula actually looks like. So here is a 144-character snippet, which animates the pendula while tracing out the trajectory of the lower pendulum:

Graphics@{Line@{{0,0},p=θ~(h={Sin@#@#2,-Cos@#@#2}&)~t,p+φ~h~t},White,{0,0}~Circle~2.2}~Show~ParametricPlot[θ~h~u+φ~h~u,{u,0,t}]~Animate~{t,0,60}

The resulting animation looks like this:

enter image description here

I had to cheat slightly: if you plot beyond t = 30, the ParametricPlot by default uses too few plot points and the line becomes quite jagged. But most of the interesting dynamics happen after that time, so I used the option PlotPoints -> 200 to make the second half of the animation looks smoother. It's nothing substantially different, and the first half would look indistinguishable anyway.

I think this will be my last snippet, unless I come up with something really mindblowing. Hope you enjoyed this!

Length 100 snippet

GeoGraphics[{GeoStyling[Opacity[0.5]], NightHemisphere[]}, GeoBackground -> GeoStyling["ReliefMap"]]

I was thinking about some nice Geo functions for the 100 snippet, but ultimately I found something really nifty on Tweet-a-Program, which I just had to steal. The above generates a very nice looking sun map of the Earth for the current time and day, by overlaying a semi-opaque shape of the night hemisphere over a relief map:

enter image description here

Length 81 snippet

CellularAutomaton[{{0,2,3,If[0<Count[#,1,2]<3,1,3]}[[#[[2,2]]+1]]&,{},{1,1}},i,n]

I promise that's the last cellular automaton. But that right there is Wireworld in 81 characters. This time I didn't encode the rule in a single number, a) because I think it would be ridiculously huge (I didn't bother figuring it out) and b) to show you yet another usage of CellularAutomaton. This time, the rule is simply specified as a pure function, which receives a cells neighbourhood and returns the cell's new value. This is a much more feasible approach for cellular automata with more than 2 colours/states.

Anyway, I've set up the example from Wikipedia in i (two clocks generating signals, and a XOR gate) and let it run for some 50 steps:

enter image description here

If you're interested, the actual plotting and animation could have been snippet 77:

ListAnimate[ArrayPlot[#,ColorRules->{0->Black,1->Blue,2->Red,3->Yellow}]&/@w]

Length 69 snippet

DSolve[r^2*R''[r]+2r*R'[r]-R[r]==0&&(R[r]==1&&R'[r]==2/.r->1),R[r],r]

Back to something useful. Apart from normal systems of equations, Mathematica can also solve systems of differential equations. The above is technically just one differential equation with boundary conditions, but you can also supply that as a system of three equations. Similar to the integrating functions DSolve is for exact solutions whereas NDSolve will solve the system numerically. The above yields a single solution

{{R[r] -> 1/2 r^(-(1/2) - Sqrt[5]/2) (1 - Sqrt[5] + r^Sqrt[5] + Sqrt[5] r^Sqrt[5])}}

which could now be easily used for further computations or plotted.

Length 64 snippet

CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},i,n]

I promised you more CellularAutomaton magic! This snippet computes Conways' Game of Life with initial condition i for n steps and gives you the result for all intermediate timesteps.

A few words about the parameters: 2 is the number of cell states. {{2,2,2},{2,1,2},{2,2,2}} gives the weights for the 9 cells in the 3x3 neighbourhood. It ensures that the cell itself is distinguishable from the sum of the 8 neighbours. {1,1} says that the CA rule depends on cells 1 step away in either direction. Finally, 224 is the actual updating rule encoded in a single number. Figuring out this number can be a bit tricky, but there's a fairly useful tutorial in the documentation. For more complicated automata, a single number won't cut it (because the number would be huge). Maybe we'll get there tomorrow! ;)

Anyway, if I feed a random grid into i and 200 into n, and send the result through an animated ArrayPlot, we can see that it's actually working:

enter image description here

Length 59 snippet

SphericalPlot3D[Re[Sin[θ]Cos[θ]Exp[2I*φ]],{θ,0,π},{φ,0,2π}]

Remember the polar plot from snippet 26? We can do the same thing in 3D! (In fact, there are two functions: RevolutionPlot3D for cylindrical polars and SphericalPlot3D for spherical polars.) Just like Graphics3D all three-dimensional plots are automatically rotatable in Mathematica, so you don't have to worry about a good camera angle upfront. The above plots something like a spherical harmonic (not quite though) and looks like:

enter image description here

Length 52 snippet

Manipulate[Plot[x^2a+x*b,{x,-3,3}],{a,.1,3},{b,0,3}]

This one is pretty nifty. Manipulate takes any expression, parameterises it with a bunch of variables, and then gives you a widget, where you can tweak the parameters and see live how the expression changes. As an expression you'll usually have some kind of plot. This is particularly useful if you're using Mathematica in lectures to demonstrate how families of solutions respond to modifying the parameters. The above shows how the a and b coefficients scale and shift a parabola:

enter image description here

Length 48 snippet

Import["http://www.google.com/doodles","Images"]

Import is a pretty powerful command. It's used both for loading files from disc and from the web. It knows quite a lot of different file formats, and for some of them (like HTML pages) it can actually extract data right away. The above downloads all images from Google's doodle page.

Length 45 snippet

EdgeDetect@ExampleData@{"TestImage","Splash"}

Time for some image processing. Mathematica comes with a whole bunch of example data, including images (like Lena), textures, 3D models and audio snippets. First, we load one of those:

enter image description here

Want to detect edges? It's a single function call:

enter image description here

Length 44 snippet

ArrayPlot@CellularAutomaton[110,{{1},0},100]

Finally, I've got enough characters to use CellularAutomaton and also render the result. :) As far as I'm aware, CellularAutomaton is the only function in Mathematica related to CAs. But Stephen Wolfram seems to consider himself number-one guy when it comes to cellular automata, so this function is incredibly powerful. The above shows pretty much its simplest usage. This simulates a 1D cellular automaton for 100 steps - and it will actually return the state of the automaton at each of those steps, so the result is two-dimensional. The rule is the first parameter, which can either be specified in detail via lists, or just encoded in a single number. For this example, I've chosen the rather famous, Turing complete, Rule 110. {{1},0} defines the initial condition: a single 1 in front of a background of zeroes. Maybe I'll show off some more features of CellularAutomaton in the future when I've got more characters available: it can simulate CAs in higher dimensions, using larger neighbourhoods and with more than two states.

ArrayPlot is another nice plotting utility which just plots a 2D list as a grid of solid colours indicating their value. In the simplest case, 0 is mappend to white and 1 to black. The result of the snippet is:

enter image description here

Length 43 snippet

HighlightGraph[graph,FindVertexCover@graph]

It's been a while since I mentioned graphs. There a lot of common graph theoretical problems built-in Mathematica, along with nice visualisation tools. The above, for a given graph, will find a minimal vertex cover of the graph, and then render the graph with those vertices highlighed. E.g. if graph is PetersenGraph[7,2] back from snippet 18, we get:

enter image description here

Length 42 snippet

Animate[Plot[Sin[t-x],{x,0,10}], {t,0,10}]

It's pretty simple to animate things in Mathematica (and they don't even have to be images). You just give it the expression to be evaluated for each frame and a bunch of parameters that should vary over the frames. The above simply animates a plot of a moving sine wave. The animation will look something like the following GIF:

enter image description here

Length 40 snippet

SortBy[PlanetData[#, "EscapeVelocity"]&]

SortBy does what you expect: it sorts a list based on values obtained by mapping a given function onto each list element. But wait, the above call doesn't contain a list at all. Since Mathematica 10, there is support for currying or partial application for some functions. This is not a language feature like in the more purist functional languages, but is just implemented manually for a whole bunch of functions where this is often useful. It means that the above snippet returns a new function, which only takes a list and then sorts by the given function. This can be very useful if this sorting order is something you'll use more often throughout your code.

And yes, there's another nice *Data function - the above will sort planet names by the planets' escape velocities.

Length 39 snippet

f[1]=1
f[2]=1
f[n_]:=f[n]=f[n-1]+f[n-2]

I promised to make the Fibonacci function more efficient. This snippet shows how trivial memoisation is in Mathematica. Note that all that's changed is an additional f[n]= in the third line. So when f is called for a new value (say f[3]), then f[3]=f[3-1]+f[3-2] will be evaluated. This computes f[2]+f[1], then assigns it to f[3] (with =, not with :=!), and ultimately returns the value for our initial call. So calling this function adds a new definition for this value, which is obviously more specific than the general rule - and hence will be used for all future calls to f with that value.

Remember that the other Fibonacci function took 4 seconds for 30 values? This needs 3 seconds for 300,000 values.

Length 37 snippet

l//.{a___,x_,b___,x_,c___}:>{a,x,b,c}

In the last snippet I mentioned patterns. These are most often used in rules, which (among other things) can be used to modify structures which match a certain pattern. So let's look at this snippet.

{a___,x_,b___,x_,c___}:>{a,x,b,c} is a rule. x_ with a single underscore is a pattern which refers to a single arbitrary value (which could itself be a list or similar). a___ is a sequence pattern (see also snippet 15), which refers to a sequence of 0 or more values. Note that I'm using x_ twice, which means that those two parts of the list have to be the same value. So this pattern matches any list which contains a value twice, calls that element x and calls the three sequences around those two elements a, b and c. This is replaced by {a,x,b,c} - that is the second x is dropped.

Now //. will apply a rule until the pattern does not match any more. So the above snippet removes all duplicates from a list l. However, it's a bit more powerful than that: //. applies the rule at all levels. So if l itself contains lists (to any depth), duplicates from those sublists will also be removed.

Length 36 snippet

f[1]=1
f[2]=1
f[n_]:=f[n-1] + f[n-2]

Time for new language features! Mathematica has a few nice things about defining functions. For a start, you can supply multiple function definitions for the same name, for different numbers or types of arguments. You can use patterns to describe which sorts of arguments a definition applies to. Furthermore, you can even add definitions for single values. Mathematica will then pick the most specific applicable definition for any function call, and leave undefined calls unevaluated. This allows (among other things) to write recursive functions in a much more natural way than using an If switch for the base case.

Another thing to note about the above snippet is that I'm using both = and :=. The difference is that the right-hand side of = is evaluated only once, at the time of the definition, whereas := is re-evaluated each time the left-hand side is referred to. In fact := even works when assigning variables, which will then have a dynamic value.

So the above, of course, is just a Fibonacci function. And a very inefficient one at that. Computing the first 30 numbers takes some 4 seconds on my machine. We'll see shortly how we can improve the performance without even having to get rid of the recursive definition.

Length 35 snippet

StreamPlot[{x^2,y},{x,0,3},{y,0,3}]

A very neat plot, which outputs the streamlines of a 2D vector field. This is similar to a normal vector plot, in that each arrow is tangent to the vector field. However, the arrows aren't placed on a fix grid but joined up into lines (the streamlines). The significance of these lines is that they indicate the trajectory of a particle (in a fluid, say) if the vector field was a velocity field. The above input looks like:

enter image description here

Length 34 snippet

Solve[a*x^4+b*x^3+c*x^2+d*x==0, x]

Mathematica can also solve equations (or systems of equations, but we've only got so many characters right now). The result will, as usual, be symbolic.

{
  {x -> 0}, 
  {x -> -(b/(3 a)) - (2^(1/3) (-b^2 + 3 a c))/(3 a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) + (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)/(3 2^(1/3) a)}, 
  {x -> -(b/(3 a)) + ((1 + I Sqrt[3]) (-b^2 + 3 a c))/(3 2^(2/3) a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) - ((1 - I Sqrt[3]) (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3))/(6 2^(1/3) a)}, 
  {x -> -(b/(3 a)) + ((1 - I Sqrt[3]) (-b^2 + 3 a c))/(3 2^(2/3) a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) - ((1 + I Sqrt[3]) (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3))/( 6 2^(1/3) a)}
}

Note that the solutions are given as rules, which I'll probably show in more detail in some future snippet.

Length 33 snippet

Dynamic@EdgeDetect@CurrentImage[]

Thanks to benwaffle for this idea. CurrentImage[] loads the current image of your webcam. EdgeDetect turns an image into a black-and-white image where edges are white and the rest is black (see snippet 45 for an example). The real fun comes with Dynamic which makes the expression update itself. So the result of this will actually stream pictures from your webcam and do live edge detection on them.

Length 32 snippet

NumberLinePlot[x^2<2^x,{x,-2,5}]

A rather unusual type of plot. It can plot a bunch of different things along the number line, like points and intervals. You can also give it condition, and it will show you the region where that condition is true:

enter image description here

The arrow indicates that the region continues to infinity. The white circles indicate that those are open intervals (the end points are not part of the interval). For closed ends, the circles would be filled.

Length 28 snippet

Graphics3D@{Sphere[],Cone[]}

Time for some 3D graphics. The above renders a super-imposed sphere and cone with default parameters, which looks something like crystal ball:

enter image description here

In Mathematica, you can actually click and drag this little widget to rotate it.

Length 27 snippet

CountryData["ITA", "Shape"]

More *Data! CountryData is pretty crazy. Getting the shape of a country is not even the tip of the iceberg. There is so much data about countries, you could probably write an entire book about this function. Like... there is FemaleLiteracyFraction. You can also query that data for different points in time. For a full list, see the reference.

enter image description here

Length 26 snippet

PolarPlot[Sin[5θ],{θ,0,π}]

Time for a more interesting plot. PolarPlot is simply a plot in polar coordinates. Instead of specifying y for a given x, you specify a radius r for a given angle θ:

enter image description here

Length 25 snippet

{{1,5},{2,3},{7,4}}.{8,9}

We've finally got enough characters for some vector maths. The above computes the matrix multiplication of a 2x3 matrix and row 2-vector:

{53, 43, 92}

Length 23 snippet

Rotate[Rectangle, Pi/2]

Heh. Hehe. You think you know what this does. But you don't. Rectangle by itself is just a named function. To actually get an object representing a rectangle, you'd need to call that function with some parameters. So what do you think happens, when you try to rotate Rectangle? This:

enter image description here

Length 22 snippet

30~ElementData~"Color"

Another of the built-in *Data functions. Yes, for chemical elements, you don't just get things like their atomic number, melting point and name... you can actually get their colour at room temperature. The above gives the colour of Zinc:

SlateGray

Length 21 snippet

Integrate[E^(-x^2),x]

We had differentiation some time ago. Time for integration. Mathematica can handle both definite and indefinite integrals. In particular, Integrate will give you an exact solution, and it can deal with a ton of standard integrals and integration techniques (for numerical results, there's NIntegrate). If you know your calculus, you'll have noticed that the above Gaussian integral doesn't actually have a closed form indefinite integral... unless you consider the error function closed form, that is. Mathematica returns:

1/2 Sqrt[π] Erf[x]

Length 20 snippet

"Sun"~StarData~"Age"

Back to built-in data. There must be at least two dozen *Data functions for everything you could possibly think of. Each of them takes an identifier for the thing you want the data for, and a property (or list of properties) to retrieve. The above is just one of the shortest you can get with Sun, Star and Age all being pretty short, because I couldn't wait to show this feature.

Oh yeah, and did I mention that Mathematica (since 9) supports quantities with units? (More on that later.) The above evaluates to:

Quantity[4.57*10^9, "Years"]

which is displayed as

enter image description here

Length 19 snippet

MandelbrotSetPlot[]

Yeah... very useful function... I use it all the time. (Sometimes, their desire to support anything that's possibly computable might go a bit far...)

Mathematica graphics

In their defence, the function is a bit more useful than that: you can give it a particular section of the graph you want to plot.

Length 18 snippet

PetersenGraph[7,2]

Since Mathematica 8, it understands what graph are, so it comes with all sorts of graph-theory related functions. And it wasn't Mathematica if it wouldn't include a ton of built-ins. The above generates the graph data for a generalised Petersen graph. It does produce the actual data structure that can be manipulated, but Mathematica immediately displays that graph data ... graphically:

Mathematica graphics

Length 17 snippet

Plot[x^x,{x,0,2}]

Finally enough characters to do some plotting. The above is really just the simplest example of a one-dimensional plot. I promise to show off cooler plots later on

Mathematica graphics

Length 15 snippet

{##4,#,#2,#3}&

This shows two of the more powerful features (and also useful ones for golfing). The entire thing is an unnamed pure function, comparable with lambdas in Python, or Procs in Ruby. Pure function are simply terminated by a &. This operator has very low precedence, so that it usually includes almost everything left of it. The arguments of a pure function are referred to with #, sometimes followed by other things. The first argument is # or #1, the second is #2, and so on.

The other feature is Sequences. These are basically like splats in other languages. A sequence is like list without the list around it - it's literally just a sequence of values, which can be used in lists, function arguments etc. ## in particular is a sequence of all pure-function arguments. ##2 is a sequence of all arguments starting from the second. So if we named the above function f, and called it like

f[1,2,3,4,5]

We would get

{4,5,1,2,3}

so the function rotates the input arguments 3 elements to the left. Note that ##4 referred to 4,5 which were flattened into the list.

Length 12 snippet

D[x^y^x,x,y]

Partial differentiation. D will differentiate the first expression successively with respect to its other arguments, giving you a symbolic expression as the result. So the above is d²(x^y^x)/dxdy (where the ds are partial), which Mathematica reports to be

x^y^x (y^(-1 + x) + y^(-1 + x) Log[x] + x y^(-1 + x) Log[x] Log[y]) + 
  x^(1 + y^x) y^(-1 + x) Log[x] (y^x/x + y^x Log[x] Log[y])

Length 9 snippet

Exp[I*Pi]

We haven't done any complex arithmetic yet! As you can see, π was actually just an alias for Pi. Anyway, the above will actually correctly return the integer -1.

Length 8 snippet

Sunset[]

Yeah. Talk about crazy built-ins. Without parameters that actually gives you a datetime object of the next sunset at your current location. It also takes parameters for other dates, other locations etc. Here is what it looks like for me right now:

enter image description here

Length 7 snippet

9!/43!!

This snippet shows off a few cool things.

Mathematica doesn't just have a built-in factorial operator !, it also has a double factorial !! (which multiplies every other number from n down to 1). Furthermore, it supports arbitrary-precision integers. The 43!! will be evaluated exactly, down to the last digit. Furthermore, rational numbers will also be evaluated exactly. So, since both numerator and denominator in there are integers, Mathematica will reduce the fractions as far as possible and then present you with

128/198893132162463319205625

Of course, you can use floats whenever you want, but in general, if your input doesn't contain floats, your result will be exact.

Length 4 snippet

Here

It's about time we started with Mathematica's wealth of crazy built-ins. The above does what it says on the tin and (for me) evaluates to GeoPosition[{51.51, -0.09}].

Length 3 snippet

x-x

Just to showcase the original Factoid: the above works even if x is not defined yet and will actually result in 0 in that case.

Length 2 snippet

3x

Multiplication via juxtaposition! If it's clear that an identifier ends and another begins, you don't need a * or even whitespace to multiply them together. This works with pretty much everything, including strings and variables that don't have values yet. Very convenient for golfing. ;)

Length 1 snippet

π

Guess what, it's Pi. And in fact, it's not some approximate floating-point representation, it's Pi exactly - so all sorts of complex and trigonometric functions this is used in will yield exact results if they are known.

Factoid

Mathematica can perform symbolic manipulation, so variables don't need values to work with them.

Answered by Martin Ender on November 19, 2021

Haskell

You might want to read from the bottom up. Sometimes I refer back to lower snippets, but never to higher ones, so it might help understanding.

Readers who do not know Haskell: am I clear? When am I not clear? I can't tell.

Length 86 snippet

A foldable instance for our tree data structure (snippet 23). Foldable is a type class - as in, a class(/group) of types. These are parallel to interfaces in Java. They essentially generalize over types, unifying types which have common characteristics; for example, they can be added together (Monoid), containers (Functor), can be printed as text (Show, which we have met already, in the show function), and so on. This one unifies data types which are list-like in that they can be iterated over or flattened to a list.

In this snippet, we define the instance by defining foldr, which essentially iterates over the data type from right to left. Now, we can use a bunch of general pre-written code. First, we define a helper function to get a singleton tree, to avoid all the clutter: s a = N E a E. Now:

sum (N (s 3) 7 (N E 5 (s 8))     === 23
product (N (s 3) 7 (N E 5 (s 8)) === 840
toList (N (s 3) 7 (N E 5 (s 8))  === [3,7,5,8]

and so on.

Here's a picture of our tree:

7
| 
3  5
    
     8

Length 70 snippet

primes=sieve[2..] where
 sieve(p:xs)=p:sieve(filter(x->x`mod`p/=0)xs)

This is a prime sieve!

(note: /= is what != is in other languages)

This works by defining a function sieve which filters the list and keeps only the numbers which are not divisible by any previous prime. It is defined recursively - to sieve is defined as to split the list to a first element p and a tail, filter from the tail any number divisible by p, sieve the remaining bit, attach p to the start of that, and return.

Again, we are working with infinite lists here - but the computation will halt in time as long as you don't require an infinite amount of primes to be computed.

take 4 primes === [2,3,5,7]

Length 68 snippet

Finally, a quine!

main=do putStr s;print s where s="main=do putStr s;print s where s="

In your first time reading this, you might think that the output of this quine would be missing the quotation marks, and why would you once write putStr and once print? It sounds the same.

In Haskell, putStr is a function that just prints the contents of the string it gets to stdout; print, though, prints things to stdout. So, print 4 is equivalent to putStr "4n", but putStr 4 is nonsensical - 4 is not a string! So, when print gets a value, it first converts it into a string, and then prints that string. Generally the way to convert things to strings is to find the way you would write it down in code. So, the way you would write the string abc in a string in Haskell code is "abc", so print "abc" actually prints "abc", not abc.

How fortunate I have enough votes now, I won't have to golf these things

Length 33 snippet:

main=go 0
go n=do print n;go(n+1)

The important thing to note is that we didn't use a loop. Haskell doesn't loop. Haskell recurses. Haskell doesn't have loops. It's deeper than that: Haskell doesn't even have Control flow. How, you might ask? Well, it doesn't need any.

On with the details. This program prints an infinite increasing sequence of integers, starting from 0. go prints them starting with its input, then main calls it on 0.

do is a special syntactic power of Haskell. In this scenario, it just combines I/O actions, just like >> does (see snippet 22).

Length 26 snippet:

map f=foldr(x y->f x:y)[]

This defines the map function, probably familiar to everyone, using foldr. Notice that although we didn't declare map's type, the computer somehow knows its type is (a -> b) -> [a] -> [b], i.e. given a function from a to b, and a list of as, return a list of bs.

How did it know?? ;-)

Length 25 snippet:

main=putStr"Hello World"

The standard Hello World. Note the types: main has type of IO () and putStr has type of String -> IO () (a function from strings to I/O actions which return nothing).

Length 23 snippet:

data T a=E|N(T a)a(T a)

This is a standard definition of a Tree. How much easier than all those lines required to define a tree in Java, C, or anything else.

(see snippet 10)

Let's break it down:

data - this declaration declares a data type. T a - a tree containing elements of type a. This is the type we are defining. = - every value of T a will be any of the following, separated by a pipe |. E - one of the possible values of T s - the empty tree. N (T a) a (T a) - the other possible value of a tree - a node. Each node consists of the left child ((T a)) the element (a) and the right child ((T a)).

Length 22 snippet:

main=putStrLn"y">>main

A Haskell yes function. >> is an operator which combines and sequences two I/O actions. It has type of >> :: IO a -> IO b -> IO b.

main is defined recursively by itself, as the I/O action which first prints "y" and then does whatever main itself does.

Length 18 snippet:

fix f=r where r=f r

A better definition for fix. (See snippet 14.) The problem with the first definition, fix f = f(fix f), is that every time we call fix f fix recalls fix f, which recalls fix f, generating endless copies of the same computation. This version fixes it by defining r (result) to be the result; as such, f r = r. So, let's define r = f r. Now we return r.

Length 17 snippet:

f n=product[1..n]

This is the functional way to define factorial.

Length 16 snippet:

f n=(x->x+x+x)n

(x -> x + x + x) is a lambda (someone thought resembles the letter.).

(x -> x + x + x) n is the lambda applied to n (this is exactly the same as n + n + n).

f is the multiply-by-three function (also f = (*3))

Length 15 snippet:

sum=foldl (+) 0

This defines the sum function using a fold. A fold is basically a loop over the elements of a list with one accumulator.
foldl takes as arguments some function f and some initial value x for the accumulator and a list xs. The function f should get as input the previous accumulator value and the current value of the list, and it returns the next accumulator.
Then the fold iterates on the list values, applying f on the previous accumulator, and then returns the last accumulator.

Another way to think about folds is like the fold 'inserts' f between the list values and with the initial accumulator in one of the sides. For example, foldl (*) 1 [4,2,5] evaluates to 1 * 4 * 2 * 5.

Length 14 snippet:

fix f=f(fix f)

The y combinator. It is usually named fix because it finds the fixpoint of the equation f x = x. Note that x = infinite loop can also sometimes a solution, so fix (x -> x^2 + 5*x + 7) won't solve the equation x^2 + 4*x + 7 = 0 but instead return an infinite loop.

You may also note that not always x = infinite loop is a solution, because of Haskell's laziness.

This version is a time and space leak; we will redefine it in a longer snippet.

Length 13 snippet:

f=sum.map(^2)

This defines the function f that given a list returns the sum of its squares. It is the function composition of the function sum and the functionmap(^2), which in turn is the function map applied to the function (^2) (the square function), which is in turn a section of the function ^ (sections were introduced at snippet 2, and composition at snippet 3).

As you can see, functions are quite important in a functional language like Haskell. In fact, it has been said that Haskell is the language with the most standard library functions which get functions as inputs or return functions as outputs (this is commonly known as a higher-order function.

By the way, technically, every two-or-more argument function is a function which returns functions as outputs (this is called currying).

Length 10 snippet:

data B=T|F

This is a definition of Haskell booleans with different names. The boolean type is named B.
This definition introduces two constructors: true (T) and false (F).
This code snippet basically tells the compiler that every boolean (B) is either true (T) or false (F), or in other words, B=T|F.

In fact, all data types ever can be defined in Haskell, when in other languages the number, references and array data types need special support from the compiler. In practice there is special support in Haskell as it would be very inconvenient otherwise, but for example the Bool datatype is defined entirely in language.

Length 9 snippet:

main=main

This nonsensical program will define main to be main. Because Haskell is lazy, values which would require an infinite loop to evaluate can be used freely if we don't use their actual value. Such values which contain infinite loops, like our main, are called "bottoms".

A fun fact is that the GHC Haskell compiler can detect these kinds of infinite loops and throw a catchable (!) exception when it is run.

Length 8 snippet:

f(x:_)=x

This defines the function f which, given a non-empty list, will return its head.

Patterns in Haskell are like Python's sequence unpacking, but generalized for all types. Patterns can either reject or match a value, and if it matches, can bind variables to values.

The patterns in this snippet are:

  • _: the pattern which matches anything and binds no variable.
  • x: the pattern which bind anything and binds it to the variable x.
  • :: this pattern gets to child patterns, that is, one for the head, and one for the tail. If the list is non empty, it matches them with the head and the tail.

Pattern matching is highly generalized. In fact, just defining new data types will automatically introduce patterns for working with them.

Length 5 snippet:

x=2:x

Whoa, there's so much to explain on this one.

First of all, Haskell is lazy. This means that subexpressions will be evaluated only when strictly necessary.

Note: this code snippet doesn't show assignment, but definition. Haskell doesn't have assignment.

This code snippet defined x, an infinite list made up entirely of 2. Usually in other languages x has to be evaluated before 2:x can ever be evaluated, but in Haskell we can do this.

Haskell infinite lists are sort of a mix of iterators and regular linked lists: they act like both (an iteration over a range will use constant memory, for example).

Length 4 snippet:

2:[]

This snippet just encodes the singleton list [2]. : is the Cons operator in Haskell. In fact, the regular list syntax is just syntactic sugar for the cons operator and the empty list literal. This tightly ties in into the way Haskell deals with Pattern matching and Data types (particularly the concept of constructor).

Length 3 snippet:

f.g

In Haskell, . stands for function composition. Haskell can be written in a "point-free" style, which is characterized by not naming function arguments and instead using the . operator to manipulate data flow.

Length 2 snippet:

1-

When this code is wrapped in parentheses (for syntactical reasons) it is called a "section". It is then a function that given some number, "fills up" the empty spot and returns one minus that number. This notion is sometimes useful in a functional language like Haskell, where otherwise a lambda would be needed.

Length 1 snippet:

1

In Haskell, 1 can be both an Int, Float, Double, Word and so forth. In fact, you can write code to define a version of 1 in any type and use it freely.
this is done too in JavaScript, Python and so forth, but unlike those, it is done with full type safety.

factoid:

Originally, the Haskell committee intended to call the language "Curry" after Haskell B. Curry's name but decided to change the name to Haskell because some puns might arise. Only later they noticed Haskell's similarity to "Pascal" and "Hassle"!

Answered by proud haskeller on November 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP