550
\$\begingroup\$

Notes

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

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

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

How this works

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

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

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

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

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

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

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

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

Current answers, sorted alphabetically by language name

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

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

243 Answers 243

1
5
6
7 8 9
10
\$\begingroup\$

𝔼𝕊𝕄𝕚𝕟

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.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ I just discovered that your title actually renders properly in firefox (it doesn't here in chrome) \$\endgroup\$ Commented Nov 15, 2015 at 20:55
  • \$\begingroup\$ For me, it renders fine on my Mac and in ChromeOS, but not in Windows 7. \$\endgroup\$ Commented Nov 16, 2015 at 22:35
  • \$\begingroup\$ I really should learn this. \$\endgroup\$ Commented Nov 17, 2015 at 8:24
  • \$\begingroup\$ I'm currently working on updating the docs... Perhaps you should look at the source code of the interpreter for now (if you are familiar with Javascript ES6). \$\endgroup\$ Commented Nov 17, 2015 at 14:20
  • 2
    \$\begingroup\$ @SuperJedi224 For the first time ever, I can see the title in all browsers! \$\endgroup\$
    – mbomb007
    Commented Dec 16, 2015 at 23:06
10
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Not sure if this applies, but if we're going by entropy, we would score a length-6 hex entry as 3 bytes as in meta.codegolf.stackexchange.com/questions/546/… \$\endgroup\$
    – lirtosiast
    Commented Jun 6, 2015 at 23:43
  • \$\begingroup\$ So... should we do that for this? \$\endgroup\$ Commented Jun 7, 2015 at 1:47
  • \$\begingroup\$ It's your choice I think; the brainfuck answer scores by characters but since this is literally hex you could score by entropy. \$\endgroup\$
    – lirtosiast
    Commented Jun 7, 2015 at 2:29
10
\$\begingroup\$

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

\$\endgroup\$
10
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 'eval is not evil' :) nice pun! \$\endgroup\$
    – sergiol
    Commented Mar 12, 2017 at 22:54
10
\$\begingroup\$

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]
\$\endgroup\$
4
  • 1
    \$\begingroup\$ 5 votes--how to assign a variable? :3 \$\endgroup\$ Commented May 4, 2016 at 13:43
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ read on and find out! \$\endgroup\$
    – Cyoce
    Commented May 4, 2016 at 15:25
  • \$\begingroup\$ What would 0=x do? \$\endgroup\$ Commented May 4, 2016 at 15:30
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ that would push 0 to the stack, but that's just a quirk of Ruby number parsing. \$\endgroup\$
    – Cyoce
    Commented May 4, 2016 at 16:21
10
\$\begingroup\$

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
\$\endgroup\$
10
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Another interesting 2 byte submission is +T, which is the Fibonacci sequence :). \$\endgroup\$
    – Adnan
    Commented Nov 12, 2016 at 18:46
  • \$\begingroup\$ You can also add a Length 6 snippet. \$\endgroup\$ Commented Nov 13, 2016 at 10:45
10
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Is it suited for golfing? \$\endgroup\$
    – lirtosiast
    Commented Aug 29, 2015 at 4:59
  • 5
    \$\begingroup\$ It probably isn't. \$\endgroup\$
    – galexite
    Commented Aug 29, 2015 at 5:25
  • 6
    \$\begingroup\$ Add some snipits? \$\endgroup\$ Commented Oct 5, 2015 at 20:44
10
\$\begingroup\$

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.

\$\endgroup\$
9
\$\begingroup\$

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.

\$\endgroup\$
9
\$\begingroup\$

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
\$\endgroup\$
9
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ I'm afraid your length-4 code snippet is five characters long? \$\endgroup\$
    – lynn
    Commented May 27, 2015 at 19:30
  • \$\begingroup\$ @Mauris Shhhh, lets keep it between us ;) \$\endgroup\$ Commented May 27, 2015 at 20:24
  • \$\begingroup\$ I coded on AS2 so I dont know if this is still a thing but one of my favorite features of AS2 was the ability to use the this. operator when adding code to an object. If I drew a mouse on stage and then selected the mouse and added the code this.x += 5; it would move 5 pixels right (as opposed to stage.layer1.mouse.x += 5; or whatever it was (It's been like 13 years since I coded in AS2 hahaha) \$\endgroup\$ Commented Feb 24, 2017 at 7:11
9
\$\begingroup\$

JSFuck

Length 6

+[![]]

Since ![] is false, [![]].toString() is "false", which isn't a valid number. Therefore, when converting to number, it returns NaN.

I decide to make it here because it's the first time we can create an uppercase letter, and uppercase letter usually take a lot of code to generate.

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.

\$\endgroup\$
8
  • \$\begingroup\$ It's not strange; increment only works on variables. \$\endgroup\$
    – ASCII-only
    Commented May 24, 2016 at 13:34
  • \$\begingroup\$ Why is [[]][+[]] a variable but not []? \$\endgroup\$
    – Leaky Nun
    Commented May 24, 2016 at 13:36
  • \$\begingroup\$ @LeakyNun I'm guessing there, but isn't [[]][+[]] technichally the value in an array's cell? hence, it's technichally a variable, alllowing to increment it. \$\endgroup\$
    – Katenkyo
    Commented May 24, 2016 at 13:40
  • \$\begingroup\$ @Katenkyo Thanks, but I still don't get it. What is [] then? \$\endgroup\$
    – Leaky Nun
    Commented May 24, 2016 at 13:47
  • \$\begingroup\$ @LeakyNun it is an array in itself, in some cases JS will allow you to use it as a pointer to its first value in the second case, you get an empty array, yes, but it is interpreted as a value as it is inside an other array -> [[]][0] vs []. In first case you have the value of an array wich is considered a variable of type "array", in the second one, you manipulate an array. \$\endgroup\$
    – Katenkyo
    Commented May 24, 2016 at 13:53
9
\$\begingroup\$

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 block

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

2 blocks

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.

\$\endgroup\$
5
  • \$\begingroup\$ The highest-ranked scoring rule you linked to scores the say block as four bytes say( plus the contents. \$\endgroup\$ Commented May 25, 2016 at 18:41
  • \$\begingroup\$ Although since it does not specify a human-language for scratchBlock output, you can also use decir( or 说( or lots of other options... \$\endgroup\$ Commented May 25, 2016 at 18:44
  • \$\begingroup\$ I'm going off the main post, not the responses. \$\endgroup\$ Commented May 25, 2016 at 18:55
  • 1
    \$\begingroup\$ ... but that's not how meta works. However, it makes sense to use "each block is one vote" for the purposes here. \$\endgroup\$ Commented May 25, 2016 at 19:45
  • \$\begingroup\$ And each character of text in text spaces is one vote. Don't forget about that. \$\endgroup\$ Commented May 26, 2016 at 16:23
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
0
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ An unbalanced parenthesis will stay with you all day... \$\endgroup\$ Commented Apr 6, 2016 at 18:08
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I have a lot of that in Cookie. :P \$\endgroup\$
    – user51533
    Commented Apr 6, 2016 at 18:58
8
\$\begingroup\$

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
\$\endgroup\$
8
\$\begingroup\$

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)

\$\endgroup\$
1
  • 2
    \$\begingroup\$ (belated) Welcome to PPCG! \$\endgroup\$
    – Cyoce
    Commented Apr 5, 2016 at 20:40
8
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ I don't think you're allowed to contain code in your factoid. \$\endgroup\$
    – Cyoce
    Commented May 1, 2016 at 1:30
  • \$\begingroup\$ @Cyo I don't think demonstrating how the empty list differs from the empty application is substantial code by this question's definition, but you're free to disagree \$\endgroup\$
    – cat
    Commented May 1, 2016 at 1:47
  • \$\begingroup\$ Fair enough. Still something interesting that wouldn't fit well into the snippet format, so I can see why you put it there \$\endgroup\$
    – Cyoce
    Commented May 1, 2016 at 7:23
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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

\$\endgroup\$
0
8
\$\begingroup\$

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)

\$\endgroup\$
11
  • 1
    \$\begingroup\$ ... I can't believe this doesn't already exist. Nice job creating it! \$\endgroup\$
    – Riker
    Commented May 4, 2016 at 14:05
  • 1
    \$\begingroup\$ @EᴀsᴛᴇʀʟʏIʀᴋ, Well, it does. =) \$\endgroup\$ Commented May 13, 2016 at 10:04
  • 1
    \$\begingroup\$ The question says: It is suggested that you choose a programming language that has not been posted already but this is not a requirement.", so it's OK for you to have another Octave entry. Personally, I suggest you don't use any of the features that's already covered in my (and possibly flawr's answers). \$\endgroup\$ Commented May 18, 2016 at 7:48
  • 1
    \$\begingroup\$ {3} creates a 1-by-1 cell array with a 1-by-1 matrix with the value, 3 in it. Creating a 1-by-1 cell array rarely has any pros, only cons. But the brackets can be used to create cell arrays with more elements too of course: {3, rand(3,2); 'This is a string in a cell', magic(4)}, in which case it's very useful. \$\endgroup\$ Commented Aug 10, 2016 at 5:34
  • 1
    \$\begingroup\$ This generates an instance of a matrix with one entry, 3. The way to do this exact task is simply one byte: 3! =) Try x = 3; y={3}; whos. You'll see that x is a 1-by-1 double, where as y is a 1-by-1 cell. y = {'This is a cell'} will also result in a 1-by-1 cell. whos y{1} will show that that specific cell element contains a 1-by-14 array of chars. You can't do y = {3}, followed by y==3 or y+3 if yis a cell, since they're not of the same class. \$\endgroup\$ Commented Aug 12, 2016 at 8:19
8
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ Good luck getting enough to make a working program. :P \$\endgroup\$
    – user48538
    Commented Sep 24, 2016 at 20:49
  • \$\begingroup\$ Where's 1 to 5? You don't have to make full programs, you know - something like skip is acceptable. \$\endgroup\$
    – clismique
    Commented Sep 26, 2016 at 7:55
8
\$\begingroup\$

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!

\$\endgroup\$
8
\$\begingroup\$

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

\$\endgroup\$
8
\$\begingroup\$

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

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
​
\$\endgroup\$
1
5
6
7 8 9

Your Answer

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

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