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

228 Answers 228

16
\$\begingroup\$

Pyke

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

1 byte:

r

Try it here!

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

1: GOTO_START

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

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

2 bytes:

SB

Try it here!

The factorial function - not a builtin. Equivalent to

product(range(1, input+1))

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

3 bytes:

]UP

Try it here!

This actually shows off 3 interesting features:

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

4 bytes

F\_+

Try it here!

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

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

5 bytes

#.b){

Try it here!

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

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

6 bytes

C695@]

Try it here!

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

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

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

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

7 bytes

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

.dॳv

Try it here!

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

A compressor for Pyke can be found here

8 bytes

1?tY/r"Z

Try it here!

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

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

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

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

9 bytes

S#2%!)1|e

Try it here!

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

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

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

10 bytes

Cy1H30M"+t

Try it here!

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

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

11 bytes

V.X".X-+||"

Try it here!

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

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

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

0: upper (all characters have this as default)

1: topleft (corners if undefined have this)

2: left line

3: right line

4: lower line

5: topright corner

6: bottomright corner

7: bottomleft corner

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

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

12 bytes

Whoever said golfing languages had far to many useless builtins?

CB"Jupiter"@

Try it here!

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

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

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

13 bytes

~1#_P)D3M*+mP

Try it here!

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

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

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

14 bytes

y0:0"w𕆠Vs5
​

Try it here!

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

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

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

0 - years

1 - months

2 - days

3 - hours

4 - minutes

5 - seconds

6 - weeks

7 - 4 years

8 - decades

9 - 12 hours

15 bytes

.dȇጾȞĶl5

Try it here!

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

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

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
\$\endgroup\$
  • 3
    \$\begingroup\$ While you don't get an upvote you must first post a single factoid about your language of choice in plain english, no code yet :-) \$\endgroup\$ – Will Lp Jan 19 '15 at 20:03
  • 2
    \$\begingroup\$ @WillP The rules say the number of characters is upvotes plus downvotes, so (your?) downvote means he can delete the whole post and post a single character thing from the language. That said, the factoid doesn't really have to do with the language anyway, rather with the program most use to write it (Visual Studio). \$\endgroup\$ – IllusiveBrian Jan 19 '15 at 20:17
  • 2
    \$\begingroup\$ @Namfuak It's upvotes minus downvotes in the way you'd expect. If I said otherwise somewhere then that's a typo. I downvoted this since it does not follow the "no code in the factoid" rule. But it could be fixed or Adam can delete this answer and try again. \$\endgroup\$ – Calvin's Hobbies Jan 19 '15 at 20:32
  • \$\begingroup\$ @Calvin'sHobbies Huh, now I reread it and that's pretty obviously what it says. Dunno how I misread it the first two times. \$\endgroup\$ – IllusiveBrian Jan 19 '15 at 20:37
  • 1
    \$\begingroup\$ Where is continuation? \$\endgroup\$ – Qwertiy Apr 21 '16 at 10:34
16
\$\begingroup\$

HQ9+

Factoid:

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

Length 1

Q

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

Length 2

9+

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

Length 3

9H9

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

Length 4

HQ9+

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

Length 5

+++++

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

Length 6

QH99QH

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

Length 7

QQQQQQQ

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

QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
(49 of them)

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

Length 8

+++Q++++

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

Length 9

BURLESQUE

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

Length 10

H+H+H+H+H+

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

Length 12

219661 beers

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

\$\endgroup\$
15
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Epidemiologists and survey statisticians also seem to love Stata. I haven't had much exposure to it so I'm excited to see where you go with this. \$\endgroup\$ – Alex A. Jan 20 '15 at 22:05
15
\$\begingroup\$

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 "1\n2\nFizz\n4\nBuzz\n...". :)

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

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

\$\endgroup\$
15
\$\begingroup\$

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.

\$\endgroup\$
15
\$\begingroup\$

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 
\$\endgroup\$
  • \$\begingroup\$ Update please.. \$\endgroup\$ – Rɪᴋᴇʀ Mar 31 '16 at 15:34
15
\$\begingroup\$

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.

\$\endgroup\$
15
\$\begingroup\$

GolfScript

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

Factoid

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

1 character

,

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

2 characters

~~

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

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

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

3 characters

-1%

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

4 characters

{+}*

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

    [a b c d e] {∘} *

==  a b ∘ c ∘ d ∘ e ∘

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

5 characters

2base

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

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

6 characters

n/.&n*

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

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

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

7 characters

{,}$-1=

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

8 characters

":n`":n`

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

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

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

9 characters

"#{size}"

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

10 characters

{9(:9.(}do

This prints:

87654321

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

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

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

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

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

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

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.

\$\endgroup\$
15
\$\begingroup\$

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 \0 well. If you are curious how to do the cat with 6 bytes which handles \0 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).

\$\endgroup\$
  • \$\begingroup\$ Very nice diagram to explain the wrapping behaviour! :) \$\endgroup\$ – Martin Ender Oct 28 '16 at 19:48
15
\$\begingroup\$

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.

\$\endgroup\$
15
\$\begingroup\$

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!

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

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.

\$\endgroup\$
  • \$\begingroup\$ Why does $H return the number of days from Dec 31, 1840? Is there something special about that date? \$\endgroup\$ – ASCIIThenANSI Sep 8 '15 at 17:25
  • 3
    \$\begingroup\$ @ASCIIThenANSI Legend has it that when Mass General was in the process of creating MUMPS, they wanted to be sure that their date system would encompass all the dates they might ever need to enter. In surveying their medical records (on paper at the time), they found that the oldest date they had on file was the birthdate of a (since-deceased) patient who was born in 1841. And so, it was decided that the MUMPS epoch would start on Jan 1, 1841. \$\endgroup\$ – senshin Sep 24 '15 at 23:26
14
\$\begingroup\$

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

\$\endgroup\$
14
\$\begingroup\$

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

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.

\$\endgroup\$
14
\$\begingroup\$

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.

\$\endgroup\$
  • 4
    \$\begingroup\$ Update, please? \$\endgroup\$ – Conor O'Brien Dec 15 '15 at 23:19
  • 2
    \$\begingroup\$ You have already 5 upvotes, could you provide some snippets? \$\endgroup\$ – nicael Dec 30 '15 at 13:18
  • \$\begingroup\$ @nicael sorry I'm lacking the time... I will delete the entry later the day. \$\endgroup\$ – Minzkraut Dec 30 '15 at 13:44
  • \$\begingroup\$ @Min Ok, though I don't think it's right to delete. Maybe someone will fill it with snippets. \$\endgroup\$ – nicael Dec 30 '15 at 13:46
  • \$\begingroup\$ @nicael I could keep the post, but it feels like having upvotes that I shouldn't have :/ \$\endgroup\$ – Minzkraut Dec 30 '15 at 14:02
14
\$\begingroup\$

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ ENOUGH TALK, DO IT NOW: GET UP! \$\endgroup\$ – fede s. Apr 25 '16 at 2:42
  • 1
    \$\begingroup\$ Passes through an abandoned answer only to discover it has got 7 total votes with only a "Length 1" snippet. \$\endgroup\$ – Erik the Outgolfer May 30 '16 at 7:03
14
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Unfortunately you won't be able to post as much since brain-flak has to have an even source code length. \$\endgroup\$ – DJMcMayhem Oct 20 '16 at 19:12
  • \$\begingroup\$ @DJMcMayhem I can use debug flags for the odd ones \$\endgroup\$ – Sriotchilism O'Zaic Oct 20 '16 at 19:13
  • \$\begingroup\$ Or you could double everything. I'm not sure how valid that is though \$\endgroup\$ – DJMcMayhem Oct 20 '16 at 19:15
  • \$\begingroup\$ @DJMcMayhem that would not be valid see: meta.codegolf.stackexchange.com/q/546/31203 \$\endgroup\$ – MegaTom Oct 20 '16 at 19:25
14
\$\begingroup\$

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!

\$\endgroup\$
  • \$\begingroup\$ Are you sure [] is falsy? Seems to be truthy on SpiderMonkey \$\endgroup\$ – Downgoat Dec 7 '15 at 2:58
  • \$\begingroup\$ @Downgoat You are correct. Apparently I was mistaken. \$\endgroup\$ – ETHproductions Dec 7 '15 at 16:57
  • \$\begingroup\$ Can i has moar snippets? You are at 11. \$\endgroup\$ – Rɪᴋᴇʀ Mar 17 '16 at 0:29
14
\$\begingroup\$

PowerShell

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

\$\endgroup\$
13
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Shouldn't it be an error since the stack is empty? \$\endgroup\$ – Adam Speight Jan 19 '15 at 21:36
  • 1
    \$\begingroup\$ @AdamSpeight The stack is never empty. The stack is initialised to a infinite number of 0. So if you do anything on the empty stack it pops a 0. But then there's still an infinite number of them. Pretty nifty. :) \$\endgroup\$ – Martin Ender Jan 19 '15 at 21:55
13
\$\begingroup\$

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

\$\endgroup\$
13
\$\begingroup\$

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

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 %d\n" n)
      (some-func (inc n)))
    (printf "loop done\n")))  ; 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 %d\n" n)
      (recur (inc n)))
    (printf "loop done\n")))  ; 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 :-)

\$\endgroup\$
  • 1
    \$\begingroup\$ Length 4 could be '(1) for an unevaluated list of length 1 \$\endgroup\$ – user100464 May 1 '16 at 3:48
  • \$\begingroup\$ @user100464 - thanks for the interesting idea. :-) \$\endgroup\$ – Bob Jarvis May 1 '16 at 13:37
13
\$\begingroup\$

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.

\$\endgroup\$
13
\$\begingroup\$

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 -> 3\n3\n3\n, 1 -> 1\n, as -> ad\nas\n. 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.

\$\endgroup\$
  • 6
    \$\begingroup\$ Snippet 4 alt #3 is a very good feature, I wish I could upvote again just for that +2 \$\endgroup\$ – Downgoat Apr 27 '16 at 1:23
  • \$\begingroup\$ Snippet 4 is my new gmail sign off. \$\endgroup\$ – Ashwin Gupta Apr 27 '16 at 1:25

Your Answer

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

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