This is no longer a popularity-contest, 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.

225 Answers
225

Mathematica

You might want to read this bottom-to-top since that's the order it was written in, and some explanations will refer to previous snippets or assume explanations from further down.

The list is growing quite long. I've started to remove less interesting snippets, and I will start skipping snippets now. See the revision history for a complete list of snippets up to 41. For some real gems, check out snippets 81, 64, 44, 23, 19, 12 and 8.

Length 143 and 144 snippets

Finally... I've been waiting for this for a while (and been golfing it for about as long, so I don't have to wait even longer). I mentioned earlier that you can also equations numerically, and that you can also solve differential equations. I wanted to show a non-trivial example of that.

Consider a double pendulum on a rod (i.e. a pendulum attached to another). Each rod has unit length and each of the two pendulum weights has unit mass. I've also used unit gravity to shorten the equation. The following 143-character snippet solves the Lagrangian equations of motion for such a system (in terms of the pendulums' angles and angular momenta). A derivation can be found in this PDF, although it's a fairly straight-forward exercise if you're familiar with Lagrangian mechanics.

What's neat is that Mathematica immediately displays a miniature plot of what the solutions roughly look like:

Okay, but that's a bit lame. We want to know what the motion of the pendula actually looks like. So here is a 144-character snippet, which animates the pendula while tracing out the trajectory of the lower pendulum:

I had to cheat slightly: if you plot beyond t = 30, the ParametricPlot by default uses too few plot points and the line becomes quite jagged. But most of the interesting dynamics happen after that time, so I used the option PlotPoints -> 200 to make the second half of the animation looks smoother. It's nothing substantially different, and the first half would look indistinguishable anyway.

I think this will be my last snippet, unless I come up with something really mindblowing. Hope you enjoyed this!

Length 100 snippet

I was thinking about some nice Geo functions for the 100 snippet, but ultimately I found something really nifty on Tweet-a-Program, which I just had to steal. The above generates a very nice looking sun map of the Earth for the current time and day, by overlaying a semi-opaque shape of the night hemisphere over a relief map:

Length 81 snippet

I promise that's the last cellular automaton. But that right there is Wireworld in 81 characters. This time I didn't encode the rule in a single number, a) because I think it would be ridiculously huge (I didn't bother figuring it out) and b) to show you yet another usage of CellularAutomaton. This time, the rule is simply specified as a pure function, which receives a cells neighbourhood and returns the cell's new value. This is a much more feasible approach for cellular automata with more than 2 colours/states.

Anyway, I've set up the example from Wikipedia in i (two clocks generating signals, and a XOR gate) and let it run for some 50 steps:

If you're interested, the actual plotting and animation could have been snippet 77:

Length 69 snippet

DSolve[r^2*R''[r]+2r*R'[r]-R[r]==0&&(R[r]==1&&R'[r]==2/.r->1),R[r],r]

Back to something useful. Apart from normal systems of equations, Mathematica can also solve systems of differential equations. The above is technically just one differential equation with boundary conditions, but you can also supply that as a system of three equations. Similar to the integrating functions DSolve is for exact solutions whereas NDSolve will solve the system numerically. The above yields a single solution

Length 64 snippet

I promised you more CellularAutomaton magic! This snippet computes Conways' Game of Life with initial condition i for n steps and gives you the result for all intermediate timesteps.

A few words about the parameters: 2 is the number of cell states. {{2,2,2},{2,1,2},{2,2,2}} gives the weights for the 9 cells in the 3x3 neighbourhood. It ensures that the cell itself is distinguishable from the sum of the 8 neighbours. {1,1} says that the CA rule depends on cells 1 step away in either direction. Finally, 224 is the actual updating rule encoded in a single number. Figuring out this number can be a bit tricky, but there's a fairly useful tutorial in the documentation. For more complicated automata, a single number won't cut it (because the number would be huge). Maybe we'll get there tomorrow! ;)

Anyway, if I feed a random grid into i and 200 into n, and send the result through an animated ArrayPlot, we can see that it's actually working:

Length 59 snippet

SphericalPlot3D[Re[Sin[θ]Cos[θ]Exp[2I*φ]],{θ,0,π},{φ,0,2π}]

Remember the polar plot from snippet 26? We can do the same thing in 3D! (In fact, there are two functions: RevolutionPlot3D for cylindrical polars and SphericalPlot3D for spherical polars.) Just like Graphics3D all three-dimensional plots are automatically rotatable in Mathematica, so you don't have to worry about a good camera angle upfront. The above plots something like a spherical harmonic (not quite though) and looks like:

Length 52 snippet

Manipulate[Plot[x^2a+x*b,{x,-3,3}],{a,.1,3},{b,0,3}]

This one is pretty nifty. Manipulate takes any expression, parameterises it with a bunch of variables, and then gives you a widget, where you can tweak the parameters and see live how the expression changes. As an expression you'll usually have some kind of plot. This is particularly useful if you're using Mathematica in lectures to demonstrate how families of solutions respond to modifying the parameters. The above shows how the a and b coefficients scale and shift a parabola:

Length 48 snippet

Import["http://www.google.com/doodles","Images"]

Import is a pretty powerful command. It's used both for loading files from disc and from the web. It knows quite a lot of different file formats, and for some of them (like HTML pages) it can actually extract data right away. The above downloads all images from Google's doodle page.

Length 45 snippet

EdgeDetect@ExampleData@{"TestImage","Splash"}

Time for some image processing. Mathematica comes with a whole bunch of example data, including images (like Lena), textures, 3D models and audio snippets. First, we load one of those:

Want to detect edges? It's a single function call:

Length 44 snippet

ArrayPlot@CellularAutomaton[110,{{1},0},100]

Finally, I've got enough characters to use CellularAutomaton and also render the result. :) As far as I'm aware, CellularAutomaton is the only function in Mathematica related to CAs. But Stephen Wolfram seems to consider himself number-one guy when it comes to cellular automata, so this function is incredibly powerful. The above shows pretty much its simplest usage. This simulates a 1D cellular automaton for 100 steps - and it will actually return the state of the automaton at each of those steps, so the result is two-dimensional. The rule is the first parameter, which can either be specified in detail via lists, or just encoded in a single number. For this example, I've chosen the rather famous, Turing complete, Rule 110. {{1},0} defines the initial condition: a single 1 in front of a background of zeroes. Maybe I'll show off some more features of CellularAutomaton in the future when I've got more characters available: it can simulate CAs in higher dimensions, using larger neighbourhoods and with more than two states.

ArrayPlot is another nice plotting utility which just plots a 2D list as a grid of solid colours indicating their value. In the simplest case, 0 is mappend to white and 1 to black. The result of the snippet is:

Length 43 snippet

HighlightGraph[graph,FindVertexCover@graph]

It's been a while since I mentioned graphs. There a lot of common graph theoretical problems built-in Mathematica, along with nice visualisation tools. The above, for a given graph, will find a minimal vertex cover of the graph, and then render the graph with those vertices highlighed. E.g. if graph is PetersenGraph[7,2] back from snippet 18, we get:

Length 42 snippet

Animate[Plot[Sin[t-x],{x,0,10}], {t,0,10}]

It's pretty simple to animate things in Mathematica (and they don't even have to be images). You just give it the expression to be evaluated for each frame and a bunch of parameters that should vary over the frames. The above simply animates a plot of a moving sine wave. The animation will look something like the following GIF:

Length 40 snippet

SortBy[PlanetData[#, "EscapeVelocity"]&]

SortBy does what you expect: it sorts a list based on values obtained by mapping a given function onto each list element. But wait, the above call doesn't contain a list at all. Since Mathematica 10, there is support for currying or partial application for some functions. This is not a language feature like in the more purist functional languages, but is just implemented manually for a whole bunch of functions where this is often useful. It means that the above snippet returns a new function, which only takes a list and then sorts by the given function. This can be very useful if this sorting order is something you'll use more often throughout your code.

And yes, there's another nice *Data function - the above will sort planet names by the planets' escape velocities.

Length 39 snippet

f[1]=1
f[2]=1
f[n_]:=f[n]=f[n-1]+f[n-2]

I promised to make the Fibonacci function more efficient. This snippet shows how trivial memoisation is in Mathematica. Note that all that's changed is an additional f[n]= in the third line. So when f is called for a new value (say f[3]), then f[3]=f[3-1]+f[3-2] will be evaluated. This computes f[2]+f[1], then assigns it to f[3] (with =, not with :=!), and ultimately returns the value for our initial call. So calling this function adds a new definition for this value, which is obviously more specific than the general rule - and hence will be used for all future calls to f with that value.

Remember that the other Fibonacci function took 4 seconds for 30 values? This needs 3 seconds for 300,000 values.

Length 37 snippet

l//.{a___,x_,b___,x_,c___}:>{a,x,b,c}

In the last snippet I mentioned patterns. These are most often used in rules, which (among other things) can be used to modify structures which match a certain pattern. So let's look at this snippet.

{a___,x_,b___,x_,c___}:>{a,x,b,c} is a rule. x_ with a single underscore is a pattern which refers to a single arbitrary value (which could itself be a list or similar). a___ is a sequence pattern (see also snippet 15), which refers to a sequence of 0 or more values. Note that I'm using x_ twice, which means that those two parts of the list have to be the same value. So this pattern matches any list which contains a value twice, calls that element x and calls the three sequences around those two elements a, b and c. This is replaced by {a,x,b,c} - that is the second x is dropped.

Now //. will apply a rule until the pattern does not match any more. So the above snippet removes all duplicates from a list l. However, it's a bit more powerful than that: //. applies the rule at all levels. So if l itself contains lists (to any depth), duplicates from those sublists will also be removed.

Length 36 snippet

f[1]=1
f[2]=1
f[n_]:=f[n-1] + f[n-2]

Time for new language features! Mathematica has a few nice things about defining functions. For a start, you can supply multiple function definitions for the same name, for different numbers or types of arguments. You can use patterns to describe which sorts of arguments a definition applies to. Furthermore, you can even add definitions for single values. Mathematica will then pick the most specific applicable definition for any function call, and leave undefined calls unevaluated. This allows (among other things) to write recursive functions in a much more natural way than using an If switch for the base case.

Another thing to note about the above snippet is that I'm using both = and :=. The difference is that the right-hand side of = is evaluated only once, at the time of the definition, whereas := is re-evaluated each time the left-hand side is referred to. In fact := even works when assigning variables, which will then have a dynamic value.

So the above, of course, is just a Fibonacci function. And a very inefficient one at that. Computing the first 30 numbers takes some 4 seconds on my machine. We'll see shortly how we can improve the performance without even having to get rid of the recursive definition.

Length 35 snippet

StreamPlot[{x^2,y},{x,0,3},{y,0,3}]

A very neat plot, which outputs the streamlines of a 2D vector field. This is similar to a normal vector plot, in that each arrow is tangent to the vector field. However, the arrows aren't placed on a fix grid but joined up into lines (the streamlines). The significance of these lines is that they indicate the trajectory of a particle (in a fluid, say) if the vector field was a velocity field. The above input looks like:

Length 34 snippet

Solve[a*x^4+b*x^3+c*x^2+d*x==0, x]

Mathematica can also solve equations (or systems of equations, but we've only got so many characters right now). The result will, as usual, be symbolic.

Note that the solutions are given as rules, which I'll probably show in more detail in some future snippet.

Length 33 snippet

Dynamic@EdgeDetect@CurrentImage[]

Thanks to benwaffle for this idea. CurrentImage[] loads the current image of your webcam. EdgeDetect turns an image into a black-and-white image where edges are white and the rest is black (see snippet 45 for an example). The real fun comes with Dynamic which makes the expression update itself. So the result of this will actually stream pictures from your webcam and do live edge detection on them.

Length 32 snippet

NumberLinePlot[x^2<2^x,{x,-2,5}]

A rather unusual type of plot. It can plot a bunch of different things along the number line, like points and intervals. You can also give it condition, and it will show you the region where that condition is true:

The arrow indicates that the region continues to infinity. The white circles indicate that those are open intervals (the end points are not part of the interval). For closed ends, the circles would be filled.

Length 28 snippet

Graphics3D@{Sphere[],Cone[]}

Time for some 3D graphics. The above renders a super-imposed sphere and cone with default parameters, which looks something like crystal ball:

In Mathematica, you can actually click and drag this little widget to rotate it.

Length 27 snippet

CountryData["ITA", "Shape"]

More *Data! CountryData is pretty crazy. Getting the shape of a country is not even the tip of the iceberg. There is so much data about countries, you could probably write an entire book about this function. Like... there is FemaleLiteracyFraction. You can also query that data for different points in time. For a full list, see the reference.

Length 26 snippet

PolarPlot[Sin[5θ],{θ,0,π}]

Time for a more interesting plot. PolarPlot is simply a plot in polar coordinates. Instead of specifying y for a given x, you specify a radius r for a given angle θ:

Length 25 snippet

{{1,5},{2,3},{7,4}}.{8,9}

We've finally got enough characters for some vector maths. The above computes the matrix multiplication of a 2x3 matrix and row 2-vector:

{53, 43, 92}

Length 23 snippet

Rotate[Rectangle, Pi/2]

Heh. Hehe. You think you know what this does. But you don't. Rectangle by itself is just a named function. To actually get an object representing a rectangle, you'd need to call that function with some parameters. So what do you think happens, when you try to rotate Rectangle? This:

Length 22 snippet

30~ElementData~"Color"

Another of the built-in *Data functions. Yes, for chemical elements, you don't just get things like their atomic number, melting point and name... you can actually get their colour at room temperature. The above gives the colour of Zinc:

SlateGray

Length 21 snippet

Integrate[E^(-x^2),x]

We had differentiation some time ago. Time for integration. Mathematica can handle both definite and indefinite integrals. In particular, Integrate will give you an exact solution, and it can deal with a ton of standard integrals and integration techniques (for numerical results, there's NIntegrate). If you know your calculus, you'll have noticed that the above Gaussian integral doesn't actually have a closed form indefinite integral... unless you consider the error function closed form, that is. Mathematica returns:

1/2 Sqrt[π] Erf[x]

Length 20 snippet

"Sun"~StarData~"Age"

Back to built-in data. There must be at least two dozen *Data functions for everything you could possibly think of. Each of them takes an identifier for the thing you want the data for, and a property (or list of properties) to retrieve. The above is just one of the shortest you can get with Sun, Star and Age all being pretty short, because I couldn't wait to show this feature.

Oh yeah, and did I mention that Mathematica (since 9) supports quantities with units? (More on that later.) The above evaluates to:

Quantity[4.57*10^9, "Years"]

which is displayed as

Length 19 snippet

MandelbrotSetPlot[]

Yeah... very useful function... I use it all the time. (Sometimes, their desire to support anything that's possibly computable might go a bit far...)

In their defence, the function is a bit more useful than that: you can give it a particular section of the graph you want to plot.

Length 18 snippet

PetersenGraph[7,2]

Since Mathematica 8, it understands what graph are, so it comes with all sorts of graph-theory related functions. And it wasn't Mathematica if it wouldn't include a ton of built-ins. The above generates the graph data for a generalised Petersen graph. It does produce the actual data structure that can be manipulated, but Mathematica immediately displays that graph data ... graphically:

Length 17 snippet

Plot[x^x,{x,0,2}]

Finally enough characters to do some plotting. The above is really just the simplest example of a one-dimensional plot. I promise to show off cooler plots later on

Length 15 snippet

{##4,#,#2,#3}&

This shows two of the more powerful features (and also useful ones for golfing). The entire thing is an unnamed pure function, comparable with lambdas in Python, or Procs in Ruby. Pure function are simply terminated by a &. This operator has very low precedence, so that it usually includes almost everything left of it. The arguments of a pure function are referred to with #, sometimes followed by other things. The first argument is # or #1, the second is #2, and so on.

The other feature is Sequences. These are basically like splats in other languages. A sequence is like list without the list around it - it's literally just a sequence of values, which can be used in lists, function arguments etc. ## in particular is a sequence of all pure-function arguments. ##2 is a sequence of all arguments starting from the second. So if we named the above function f, and called it like

f[1,2,3,4,5]

We would get

{4,5,1,2,3}

so the function rotates the input arguments 3 elements to the left. Note that ##4 referred to 4,5 which were flattened into the list.

Length 12 snippet

D[x^y^x,x,y]

Partial differentiation. D will differentiate the first expression successively with respect to its other arguments, giving you a symbolic expression as the result. So the above is d²(x^y^x)/dxdy (where the ds are partial), which Mathematica reports to be

Length 9 snippet

Exp[I*Pi]

We haven't done any complex arithmetic yet! As you can see, π was actually just an alias for Pi. Anyway, the above will actually correctly return the integer-1.

Length 8 snippet

Sunset[]

Yeah. Talk about crazy built-ins. Without parameters that actually gives you a datetime object of the next sunset at your current location. It also takes parameters for other dates, other locations etc. Here is what it looks like for me right now:

Length 7 snippet

9!/43!!

This snippet shows off a few cool things.

Mathematica doesn't just have a built-in factorial operator !, it also has a double factorial !! (which multiplies every other number from n down to 1). Furthermore, it supports arbitrary-precision integers. The 43!! will be evaluated exactly, down to the last digit. Furthermore, rational numbers will also be evaluated exactly. So, since both numerator and denominator in there are integers, Mathematica will reduce the fractions as far as possible and then present you with

128/198893132162463319205625

Of course, you can use floats whenever you want, but in general, if your input doesn't contain floats, your result will be exact.

Length 4 snippet

Here

It's about time we started with Mathematica's wealth of crazy built-ins. The above does what it says on the tin and (for me) evaluates to GeoPosition[{51.51, -0.09}].

Length 3 snippet

x-x

Just to showcase the original Factoid: the above works even if x is not defined yet and will actually result in 0 in that case.

Length 2 snippet

3x

Multiplication via juxtaposition! If it's clear that an identifier ends and another begins, you don't need a * or even whitespace to multiply them together. This works with pretty much everything, including strings and variables that don't have values yet. Very convenient for golfing. ;)

Length 1 snippet

π

Guess what, it's Pi. And in fact, it's not some approximate floating-point representation, it's Pi exactly - so all sorts of complex and trigonometric functions this is used in will yield exact results if they are known.

Factoid

Mathematica can perform symbolic manipulation, so variables don't need values to work with them.

\$\begingroup\$@durron597 By keeping it as a symbol and making all your trigonometric and complex functions aware of what to do with a π.\$\endgroup\$
– Martin EnderJan 22 '15 at 17:44

16

\$\begingroup\$Once I saw that the legendary Martin Büttner had posted a Mathematica answer, I knew I had no chance at winning a popularity contest. You sir are a true wizard.\$\endgroup\$
– Alex A.Jan 23 '15 at 16:41

Shakespeare's code resembles, as one would expect, a Shakespeare play, where the variables are characters on the play and their value changes as they are "insulted" or praised".

Length 1 snippet:

I

Shakespeare's code is divided in Acts, and the acts are themselves divided in Scenes, for "jump-to" causalities. Defining an Act as Act I means that it will be the first piece of the code to be run, per example - but not only.

Length 2 snippet:

as

Used in a comparative between two "characters".

Length 3 snippet:

day

By now, you may be getting the feeling that SPL is very verbose. And weird. And you've seen nothing yet. day, in SPL, is 1. All "positive" and "neutral" nouns are considered as 1, as well as all "negative" ones are -1.

Length 4 snippet:

rich

What is rich? An adjective. In SPL, adjectives make the value of the noun they're attached to multiply by two. See implementation on snippet 14.

Length 5 snippet:

Act I

Implementation of the first snippet. All acts may be given a title, such as Act I: Hamlet must die!, since everything after the Roman numeral is ignored by the parser.

Length 6 snippet:

better

Every language has conditions, and SPL is no exception. Except, since this is a language with a lengthy syntax (and did I mentioned it to be weird?), its conditional statements are going to be long. Having Ophelia ask Juliet Am I better than you? is like having if (Ophelia > Juliet) on most "normal" languages. And, of course, you can ask the other way around: Am I not better than you? is the equivalent of if (Ophelia < Juliet). And you can already guess how the = is translated to SPL: as good as - usage of code snippet 2.

However, good/better is not the only way to make comparisons in this shakesperian language, you can use any adjective. The same principle of snippet 3 applies here as well, with "positive" adjectives having the value >, while "negative" ones mean <.

Length 7 snippet:

Juliet:

This is the invocation of a variable; after this, his/her instructions/declarations/whatever will follow.

A limitation of SPL is that it has a limited number of variables: Romeo, Juliet, Hamlet, Ophelia, MacBeth and so on are a few examples of "characters" that will appear on a Shakesperian program.

Length 8 snippet:

[Exeunt]

[Exeunt] is placed when all "characters" leave the "stage". Hopefully I can elaborate a bit more later on about the interaction between characters. Generally is the last instruction of any SPL program, although [Exeunt] isn't specifically the terminal "character" of the language. For another example, see snippet 27.

Length 9 snippet:

as bad as

Nine characters just to represent a mere = - using snippet 2. Have I mentioned that SPL is weird? See snippet 30 for examples.
(and yes, there's more than one way to output it)

Length 10 snippet:

difference

A fancy way of representing -, a subtraction. You can have math operations on SPL, even though you'll probably need a full day to get it right.

Factoid(since I managed somehow to reach ten snippets of code, let's take a bit of a break and have another factoid about SPL)

If you want to run your shakesperian code in all its glory, there's this site - I'm still testing it, since I discovered it not even five minutes ago. There's also a way to translate it to C using a translator.

Another site for running SPL code is this one that works by internally translating the SPL code to another esoteric language: Oracle PL/SQL.

Length 11 snippet:

[Exit Romeo]

Yes! At last I can talk about the interaction between characters! In order to have its value changed or to interact with others, a "character" must be on stage - entering with [Enter Romeo]. If a character is addressed to but is not present, there's a runtime error and the program stops. Because, in SPL, the value of the variables is set by the amount of names they're praised with - or insulted with - by the other characters on stage. I feel that I should put an example to clear some confusion my lame explanation may create, but perhaps it's best to delay that a few snippets.

Length 12 snippet:

Remember me.

SPL is pretty "basic", alright - but it has stacks! When, per instance, Romeo tells Juliet to "remember him", he's actually telling his loved one to push the Romeo's value into her stack. Popping the value is done with Recall your happy childhood!, or Recall your love for me, or basically any sentence that begins with Recall - the rest is just artistic drivel, like snippet 22.

Length 13 snippet

Let us return

The Shakesperian way of having a goto. And this is where the Acts and Scenes come in handy. If Romeo tells Juliet we shall return to Act II (yes, again, there are multiple ways of write it), the program will jump to that specific part of the code. It's also seen alongside conditional statements.

Length 14 snippet

my little pony

Yes, it was a series back in the 80s. Here, it's 2*1. Why? Because a pony is a (somewhat) positive noun and little is an adjective. So, remembering snippets 3 and 4, we have little = "2 *" and pony = "1".

Length 15 snippet

Speak thy mind!

In a SPL program, you'll see this (or Speak your mind!, which is the same) a lot. This basically outputs the value of each "character" in digit, letter or anything else, depending on the character set being used by your computer. There's also Open your mind. that does almost the same thing, albeit only outputting in numeric form.

Length 16 snippet

You are nothing!

When someone tells you this in real life, you'll feel depressed. When Ophelia tells this to Hamlet in Shakespearian programming, Hamlet feels worthless. What does this mean? That Hamlet = 0.

Length 17 snippet

Ophelia, a wench.

In a screenplay, before the actual play starts, the characters must be presented. In most programming languages, the variables must also be declared before use. Seeing that SPL is a programming language that resembles a screenplay, this is how you declare its variables, by stating which are the ones appearing during the program.

But what does "a wench" mean? Does it mean that it's a specific (and cool) data type name? Well... I hate to disappoint you, but it means nothing: everything after the comma is disregarded by the parser, meaning you can put there the most outrageous drivel you can think of.

Length 18 snippet

lying sorry coward

-4 for all earthly creatures. Why? Because 2*2*(-1) = -4.

Length 19 snippet

Romeo:
Remember me.

At last!!! I can finally output a full correct syntax instruction (albeit a short one)! This is how you use snippet 12: firstly you declare who's talking, then on the next line you write the "dialogue". Normally, only two "characters" are on stage, to avoid making the parser sad and confused. When you need another "character", you take one from the stage and replace him by the new one.

Length 20 snippet

cube of thy codpiece

I wanted to elaborate a bit more for this one, but, truth be told, the things I come up with are still too short for this snippet length. And, so, I bring you this, which ends up being -1 - because (-1)3 = -1 (and codpiece is a "negative" noun, since they're uncomfortable and all). SPL understands a few more elaborate arithmetic operations as some exponentiation and square roots.

Factoid(yet another one, since we've reached another milestone)

The "Hello World Program" in Shakesperian has 89 lines and more than 2400 characters long, as seen here.

Length 21 snippet

Listen to your heart.

In snippet 15 you outputted something; here, you input a number to the program. If you want to input a character, you'll use Open your mind. instead. And, needless to say, this value will be stored in the "character" being spoken to.

Length 22 snippet

Recall your childhood!

Popping an integer from a stack is done with this, as explained on snippet 12. When, per instance, Ophelia tells Hamlet the aforementioned sentence, it causes Hamlet to take an integer from his stack and assume that value.

Of course that, as long as the word recall is starting the sentence, you can fill in the rest with pretty much anything your creative shakesperian mind desires.

Length 23 snippet

Are you better than me?

Implementation of snippet 6. When a "character" makes a question like this to another, what he/she is doing is equivalent to if (x > y) on more common programming languages. The follow-up of this instruction must be delayed until I have more characters available.

Length 24 snippet

[Enter Romeo and Juliet]

Yes, "characters" may enter in pairs. It's not required to have one "character" entering the stage, being followed by another.

Length 25 snippet

remainder of the quotient

25 characters just to write a %. 25 characters to have the remainder of a division. And to use it? Well, that's even bigger - see snippet 75.

Length 26 snippet

Let us return to scene II.

Here it is, a goto in SPL, which works as one would expect in a programming language. A thing is: you can jump between scenes in the same act, and between acts; but you cannot jump between scenes in different acts.

Length 27 snippet

[Exeunt Ophelia and Hamlet]

When more than one "character" leave the stage, instead of Exit, and keeping in tradition with SPL's theatrical nature, the latin word "Exeunt" is used. Sometimes it can be replaced just by snippet 8.

Length 28 snippet

Scene I: Ophelia's flattery.

Declaring a Scene. As you can already expect if you've been coping with me, the important bit is the Scene I, the rest is artistic fluff.

There have been some compilers made (like this one that compiles from SPL to C, written in Python) that instead refer to the text after the numbering of the Act/Scene. While more logical (after all, during a play, having the characters saying lines such as "let us return to Act I" may be deemed silly), I'm sticking to the original way.

Length 29 snippet

You pretty little warm thing!

Yes, yet another constant (since we need way more characters to have arithmetic operations). This one is equal to 8, because 2*2*2*1 = 8.

This language was created for an assignment in a Syntax Analysis course - thus, no SPL compiler was created by the authors. More: it seems SPL's authors have severed their ties with their creation, since nothing appears to have been modified in the language since 2001...

Length 31 snippet

Am I as horrid as a flirt-gill?

Yes, I know, it's somewhat repeating snippet 23, although, here, we're comparing the "character" who speaks with a "flirt-gill" (of, if you prefer, if (Ophelia == -1)). The thing is...

Length 32 snippet

If so, let us return to scene I.

... now I can introduce the then of SPL, and the conditional jump-to, and the Shakesperian way of implementing loops. You can, per instance, make Romeo assume the value 0, increment his value while doing some other task and stop when he reaches 10, proceeding with the program afterwards.

Length 33 snippet

If not, let us return to scene I.

Just a reminder that, instead, we can instead proceed forward to another scene if the condition we tested for is false.

Length 34 snippet

Open your mind! Remember yourself.

Two instructions in a row, yippie! The first one reads a character, the second one pushes it into the other character's memory stack.

Length 35 snippet

Act I: Death!
Scene I: Oh, shit.

The proper way of declaring an Act and a Scene. Add artistic mush tastefully.

Length 36 snippet

Thou art as sweet as a summer's day!

Another way of saying that the "character" being spoken to will receive the value 1 - because summer's days are nice and pleasant.

Length 37 snippet

Art thou more cunning than the Ghost?

Ophelia asking this question to Hamlet means, translating this to a less readable programming language, if (Hamlet > the Ghost). It's snippet 23 all over again, yeah - but it goes to show you that it's not required to ask the "characters" if they are better than each other: any other question will work too.

Length 38 snippet

[Enter the Ghost, Romeo and the Ghost]

Yes, I'm calling a "character" twice - because I wanted to have the program give me an error. Calling a "character" that's already on stage, or telling one that's absent to exit, will cause great grief to the parser/compiler.

Length 39 snippet

the sum of a fat lazy pig and yourself!

The full instruction is more better looking that this, I'll give you that, but... here's our first arithmetic operation! What does it all mean, actually? Well, pig is a dirty animal (albeit tasty), so it's equivalent to -1, has two adjectives, meaning fat lazy pig equals 2*2*(-1) = -4. But what about yourself? It's a reflexive pronoum, not a name nor an adjective. Well, remember that SPL is based on dialogues between "characters"; thus, yourself refers to the other "character" on stage. So, we arrive at the end and we discover that "the sum of a fat lazy pig and yourself" is, in fact, -4 + x.

Length 40 snippet

the sum of a squirrel and a white horse.

Yes, another sum, but this one is simpler than snippet 39. This is merely 1 + 2 - 3, if my math is correct.

Factoid(still with me after these forty snippets of artistic fluff? You deserve a prize.)

Sometimes, "characters" are only called on stage to have their value changed - which, on a real play, would be something quite bizarre. Anyway, here, Juliet makes her beloved Romeo print his stored value, after which he exits the stage.

Length 42 snippet

Speak YOUR mind! You are as bad as Hamlet!

Again two instructions in one line (we can have multiple, but the snippet length doesn't allow it yet); here we have a "character" telling another to output its value and assume whichever value Hamlet has. Confusing? Mayhap.

Length 43 snippet

Am I as horrid as a half-witted flirt-gill?

Juliet asking this doesn't mean she has low-esteem (although it might in real-life); it's simply another if, like snippets 23 and 37. Oh, I almost forgot: this translates to if (Juliet == -2).

Length 44 snippet

You are as evil as the square root of Romeo!

Yes, square roots are evil, didn't you know? Anyway, this instruction is straightforward enough to understand what it does: attributes the "character" being spoken to the value of the square root of the value stored in Romeo.

Length 45 snippet

Hamlet:
Art thou more cunning than the Ghost?

Snippet 37 properly written with the character who's speaking the line.

Length 46 snippet

the product of a rural town and my rich purse.

Okay... anyway, SPL may be the only language in the world that allows you to multiply towns with purses. This means (2*1)*(2*1) which, if I'm not very mistaken, is equal to 4.

Length 47 snippet

Romeo:
Speak your mind.
Juliet:
Speak YOUR mind!

I'll give you that: it may be one of the most bizarre dialogues in history. But it's what you get when you choose a weird language to showcase. Romeo and Juliet are telling each other, in short, to output their values.

Length 48 snippet

You lying fatherless useless half-witted coward!

Translating it directly, 2*2*2*2*(-1). -16, right?

Length 49 snippet

Scene V: Closure.
Hamlet:
Speak your mind!
[Exeunt]

An example of how to terminate a program in SPL. You can declare a scene specifically for it (although it's not required), then Hamlet asks another "character" to output their value, then they all exit the stage. And yes, it's required for all of them to get off the stage.

Length 50 snippet

Othello, a young squire.
Lady Macbeth, an old fart.

More "character" presentation, before the proper instructions. As always, the only thing that matters to the compiler is Othello and Lady Macbeth, so the rest of the line is up for grabs...

One more thing: the "characters" don't have to be related to each other in order to appear in a SPL program - so you can have Romeo, Othello and Hamlet on the same play.

Factoid(half-a-century of these things? Phew! After this I think I'm going to loathe William Shakespeare...)

The SPL to C translator, mentioned a while ago and developed by the SPL creators, was based on Flex and Bison.

Length 51 snippet

Othello:
Recall your great dreams. Speak your mind!

(So sick of Romeo, Juliet and Hamlet... let's bring in Othello, for a change!)

Recall, as you can guess, is the key here. The "character" Othello is addressing will take a value from his/her stack, assume that value and, afterwards, will output it.

Length 52 snippet

Thou art as pretty as the sum of thyself and my dog!

Another sum. Yawn. Assuming this one is addressed to Hamlet, means that Hamlet = Hamlet + 1. Or Hamlet += 1. Or Hamlet++.

Length 53 snippet

Romeo:
You are as vile as the sum of me and yourself!

Ah, yes, something I forgot to mention before: the speaking "characters" can mention themselves on their own lines.

Length 54 snippet

Juliet:
Is the sum of Romeo and me as good as nothing?

Another example of the previous snippet, included in a condition. So what we have here is if (Romeo + Juliet == 0).

Snippet 48 properly done, with a "character". If you're too lazy to scroll up (like I'd be), this means the one being insulted is receiving the value -16.

Length 57 snippet

Romeo:
If not, let us return to Act I. Recall thy riches!

I've already explained how conditions work on SPL on a general basis; however, a more inline analysis is needed. We don't have else in here: per instance, in this example, if the condition failed, the program would return to Act I; but if it were true, it would continue to the next instruction, which is a Recall - a pop from the stack, that is.

Length 58 snippet

Romeo:
You are as disgusting as the square root of Juliet!

Grabbing snippet 44 and presenting how the instruction should be presented. If this was a dialogue between Romeo and Othello, then we could translate this to Java as Othello = Math.sqrt(Juliet).

Length 59 snippet

Othello:
You are as vile as the sum of yourself and a toad!

OK, if Othello is talking to Romeo, this would be equivalent to Romeo+(-1); Romeo--, for short. Pretty basic, right? That's SPL for you.

Length 60 snippet

Is the quotient between the Ghost and me as good as nothing?

For short, if (The Ghost/Hamlet == 0), assuming the "me" belongs to Hamlet.

Length 61 snippet

Thou art as handsome as the sum of yourself and my chihuahua!

Once you peel away the layers and layers of words and insults, you notice that SPL is pretty much a basic thing, without cool functions and stuff. So we have loads and loads of arithmetic functions on the program's body. So, if this one was addressed to Juliet, it would be equivalent to Juliet++.

Length 62 snippet

twice the difference between a mistletoe and a oozing blister!

Yes, yes, more arithmetic operations. Roughly, these 62 bytes of SPL can be translated to 2*(1-2*(-1)). This would be a pretty awesome golfing language, right? Right.

Length 63 snippet

You lying stupid fatherless rotten stinking half-witted coward!

Snippet 48 outputted -16, this one is equal to -64: 2*2*2*2*2*2*(-1).

Length 64 snippet

your coward sorry little stuffed misused dusty oozing rotten sky

From what I understand of SPL, this is perfectly legit. You have a whole lot of insulting adjectives what proceed a "positive" noun. Since adjectives have no special distinction whether they're negative or not (their only value is multiplying the number at their right by two), we can have completely silly sentences like this one. Which is equivalent to 256. Because 2*2*2*2*2*2*2*2*1=256.

Length 65 snippet

You are nothing! You are as vile as the sum of thyself and a pig.

Hmm, so much hate, isn't it? So, what we have here is equivalent to y=0; y=y+(-1); Probably could have been "golfed" to You are a pig!, but heh.

How most conditions work on SPL. You test the expression and, if it's true (or not: see snippet 33), you jump to another part of the program; otherwise, you'll continue on to the next sentence.

Length 68 snippet

The Ghost:
You are as small as the sum of yourself and a stone wall!

Yes, yes, I'm getting a bit monotonous. But SPL is like that. As I stated a bit earlier, its expressions are a mixture of arithmetic operations. Thus, this is yet another incrementation - since stone wall is a neutral "noun".

Length 69 snippet

Thou art as disgusting as the difference between Othello and thyself!

Instead of a sum, we have the subtraction between two characters, Othello and whoever is being spoken to.

Length 70 snippet

You are as handsome as the sum of Romeo and his black lazy squirrel!

We return to the additions, yes - call me formulaic, heh. We translate this to Romeo + 2*2*1.

Four instructions in a row?! I'm quite proud of myself, actually. Anyway, let's assume this is a dialogue between Romeo and Juliet (and he's speaking): this means that Juliet's value starts at 0; then, Juliet will push Romeo's value into her stack of memory, pop it and output it in its entered form. Simple, right?

Length 74 snippet

You are as sweet as the sum of the sum of Romeo and his horse and his cat!

Yeah, yeah, boring example, I know. But this is X = (Romeo + 1) + 1.

Length 75 snippet

Is the remainder of the quotient between Othello and me as good as nothing?

Well, this is pretty straightforward. If your decoding skills are malfunctioning, it translates to if (Othello % X == 0).

Length 76 snippet

Thou art as rich as the sum of thyself and my dog! Let us return to scene I.

The jump from snippet 26 with an expression before it. A goto on SPL isn't always found near a condition, it can be like this - and, of course, this type of goto will always be found at the end of an Act or Scene, since instructions after it will never be compiled/performed. The first instruction is pretty simple: x=x+1.

So, we have Juliet and Hamlet on stage; but we're in need of the value from Romeo. Thus, in order to spare the compiler from a very nasty headache, firstly we remove Hamlet from the stage (though it could have been Juliet the one to go), we tell Romeo to get on stage, Juliet gives him an instruction to output a number (see snippet 21's explanation), then Romeo gets out of the stage and Hamlet returns. Pretty straightforward and simple.

\$\begingroup\$This incredibly interesting and your profile picture is a perfect fit, he looks precisely like what I imagine an SPL programmer would look like.\$\endgroup\$
– overactorJan 22 '15 at 9:34

3

\$\begingroup\$@overactor I don't know whether to be insulted or proud to be likened to a Gumby. ^_^\$\endgroup\$
– Rodolfo DiasJan 22 '15 at 9:59

9

\$\begingroup\$Bizarrely this is NOT the most obscure to read example here... and seems to be tied for "least practical".\$\endgroup\$
– H.R.RamblerJan 23 '15 at 16:46

6

\$\begingroup\$ROFL here's +1 to help you on the way - Once more unto the breach Rodolfo!\$\endgroup\$
– H.R.RamblerJan 24 '15 at 14:31

3

\$\begingroup\$@RodolfoDias You can begin. I'm waiting to see them. You have 120 up-votes.\$\endgroup\$
– ghosts_in_the_codeNov 13 '15 at 15:52

Piet is a programming language where the source code consists of images. Program flow starts with the top-left pixel and moves around the image between pixels and pixel groups until it terminates.

For legibility, Piet programs are commonly displayed in an enlarged version. In such a case the term codel is used to describe a group of same-coloured pixels that correspond to an individual pixel in the source image.

For this challenge, since Piet does not use characters, one codel per vote will be used for sample programs.

1 Codel

This is a valid program, it does nothing and terminates. The control flow starts in the top-left (only) pixel and has no way out, which ends the program.

The pixel can in this case be any colour for the exact same effect.

2 Codels

This will continually read characters from stdin and keep a running total of their unicode values (though nothing is done with this total and it is not displayed).

Progam flow moves back and forth between the 2 codels, since the only way out of each one is into the other. Commands in piet are executed by movement from one codel or region into another, depending on the difference in hue and lightness of the 2 regions. The input is the command moving left-to-right and then the add is right-to-left. On the first add command, nothing will happen since there is only one value on the stack, and the specification says that commands without enough values available are ignored.

This program is a loop that will never end, as most piet programs will be at extremely small sizes, since it takes at least a few codels to properly "trap" the program flow and end it.

3 Codels

This is a basic echo-type program, it will read a character at a time from stdin and print it to stdout.

Again this is an infinite loop. The program starts by travelling left-to right, which does the input then output. The program will continue to flow in the same direction whenever it can. At the light green codel the only exit is to start moving back the other way. When travelling back right-to-left it attempts to perform subtract and add commands, but the stack is empty so these become no-ops.

4 Codels

Prints out 2 to stdout indefinitely.

Not a particularly interesting program functionally, but now that we finally have a composite number of codels we can show off slightly more advanced flow than left-to-right. When program flow attempts to exit a codel it first tries the current direction. If it's unable (in this case due to the edge of the image) it rotates 90 degrees clockwise and attempts to exit again. In this case, the program goes around clockwise 1 codel at a time, pushing 1 onto the stack twice, adding the ones together, then outputing the result.

5 Codels

Repeatedly reads a character at a time from stdin and tracks the sum of their unicode values.

This is essentially the same functionality as the 2-codel version, but this challenge is about showcasing the language, and one of the cool things about piet is how you can have different-looking pictures that do the same thing.

Here we see the white codel for the first time, which allows program flow to slide across it without executing instructions. The magenta and blue codels do all the work here. Travelling from blue to red does nothing because it crosses the white codel in the middle. The 2 red ones just push the number 1 onto the stack and pop it back off as it travels left-to-right then right-to-left across them, and then across the white codel so no instruction is executed.

6 Codels

Again, repeating earlier functionality with a different look. This is another echo program that reads a character at a time from stdin to stdout.

Here we see our first black codel. Program flow cannot enter a black codel, so from the light magenta codel in the top-right the program will fail to exit right due to the image edge, fail to exit down due to the black codel, and bounce back left into the red codel. The blue and green codels are purely decorative, the program will never enter them.

7 Codels

Yet another echo program with a different look.

Here we see our first codel blocks larger than size 1. In piet, any contiguous block of codels of the same colour is treated as a single block. The size of the block does not matter except when executing the push instruction, so this program is treated exactly like the 3-codel version, except with different colours.

8 Codels

Reads a number from stdin and outputs the square to stdout, repeatedly.

Control flow is a basic clockwise pattern just as in the 4-codel program. Starting from the top-left, the operations in order are input, duplicate (pushes an extra copy of the top value of the stack onto the stack), multiply, output. Then it pushes the value 1 onto the stack, slides across the white so no command is executed, and then pops that 1 off of the stack when moving from the lower-left to upper-left codel. This returns it to the beginning of the program with an empty stack, and it repeats.

9 Codels

Adds 1 + 2 = 3, and then terminates.

Now that we have a program with greater than 2 codels in both dimensions, we can finally set up a region that will trap the program and end it instead of looping forever. The first operation moving from the red codel to the dark red region is a push of 1, then the program rotates and flows down into the light red codel in the middle and pushes a value of 2. Flowing from the light red to the light yellow executes an add operation. The bottom light yellow bar causes the program to end since there is no way for it to flow out as all the corners are blocked off.

The 1- and 2-high programs are quickly becoming ugly and uninteresting so from this point on I'm going to focus on numbers that allow at least a few codels in each direction.

12 Codels

Finally a program that does something that could be argued as useful (though it's still a bit of a stretch). Reads 2 numbers from stdin sequentially and then outputs their sum, and does this repeatedly.

Program flows left-to-right across the 4 coloured bars perfoming 2 inputs followed by an add command. It then moves into the lower-right codel and performs an output, and then goes left across the white region back to the start.

This could have been done in 8 codels, but since we have the extra space we can make something that's a little bit inspired by an old no-signal TV display.

15 Codels

Reads a number from stdin and outputs its' square.

This uses a couple of tricks to get a bit of a symmetrical look to a program that actually does something. The leftmost red bar is a different colour on the bottom codel than the rest, taking advantage of the fact that (for me at least) these 2 shades of red look very similar. the program will move from the lighter red region right into the light blue codel, and then straight across the middle of the program to the light green on the right side where it is trapped. It performs input, duplicate, multiply, and output operations.

The darker red codel, along with the medium green codels on the top and bottom of the middle column, are decorative and the program will never reach them.

20 Codels

Reads numbers from stdin until a 0 is read, at which point it outputs the sum of all entered numbers and exits.

We finally have enough room to do control flow in the form of the pointer operation. The 4 codels along the top perform input, duplicate, and not operations, and then another not operation moving from the magenta in the top-right to the 2-codel yellow below it. The not operation pops the top value off of the stack and pushes a 1 if the top value was a 0, and a 1 otherwise. Therefore a double-not replaces any nonzero value with a 1. Moving from the yellow bar down to the dark blue performs a pointer operation, which pops the top value off of the stack and moves the direction pointer clockwise that many times.

If the top value is a 1 (i.e. we didn't enter a zero) the direction pointer will point left, moving to the magenta codels for an add operation (which will be ignored the first time due to only one value on the stack) and then through the white back to the start of the program.

If the top value of the stack is a zero at the pointer operation, the direction pointer will not change and the program will continue downwards. Moving into the lighter blue band will pop the 0 that was entered off of the stack, leaving only the sum of the accumulated numbers. Moving into the cyan bar on the bottom will output that sum, and then end since the program flow is trapped.

25 Codels

Countdown! Reads a number from stdin, and then prints a countdown to 1 to stdout one number at a time. For example, if 5 is read, will print 54321.

The first operation from cyan to yellow is the input. Then the yellow is where the program "loop" starts. Yellow > Magenta > Blue is a duplicate then an output, so it prints the top value on the stack but keeps a copy. Moving down the right side, we push the value 1 onto the stack then perform a subtraction, decreasing our entered value by 1. Next is duplicate, not, and another not moving from the light magenta in the bottom-right to the dark yellow beside it. This is the same zero/nonzero check as the previous program. Moving left into the light blue codel performs a pointer operation, that will either move left into the dark cyan to end the program if we're done, or up to the yellow to re-start our loop without the initial input but the original value decreased by 1.

All 3 of the red codels are decorative and could be any colour.

30 Codels

Fibonacci generator. Prints out terms of the Fibonacci sequence to stdout and doesn't stop.

This is the first introduction of the roll operator, as well as the first time that a region size bigger than 1 is used with the push operator to get a specific value onto the stack.

As always starts in the top-left moving right. The first 2 operations push a 1 onto the stack and then output it since the Fibonacci sequence starts with two 1s, but the main program loop will only print 1 once. Then it pushes 2 more 1s onto the stack to end up in the dark magenta in the top-right to start the main program loop.

Moving down the right side we duplicate and output to print off the next term of the sequence, then duplicate again to get a copy of the current sequence value. Moving left across the bottom executes 2 push operations. Since the light red region in the bottom-right is 3 codels in size, the first push will push a 3 onto the stack instead of a 1.

Moving up into the light blue is a roll operation. This pops the top 2 values off of the stack and performs a number of rolls equal to the first value popped, to a depth equal to the second value popped. In this case, it will perform 1 roll to a depth of 3. A roll to depth n takes the top value of the stack (our duplicated current value) and buries it n places deep. Our stack is only 3 deep right now so it will bury the top value at the bottom.

Moving up once more performs an add operation adding together the current sequence value with the previous sequence value. Our stack now has the next (new current) sequence value on top, and the last value below it. The program now moves right across the white into the dark magenta to start the loop again.

The yellow pattern in the middle is never used.

54 Codels

Prints "hi!" to stdout

Not a particularly long message, but printing in piet takes a surprising amount of room. Printing is done by using unicode values, and integers are pushed onto the stack by using the size of the region that is being exited. Since we have a very limited number of codels for this challenge, we use some math to get up to the printable range we want.

The program starts with a push of 5 from the cyan region on the left. From here, it flows right along the top with 6 duplicate operations to prime the stack with a bunch of 5s. Next is push 1, subtract to put a 4 on top of the stack, then 2 multiply operations to put 4*5*5=100 on top of the stack. Then a duplicate for 2 100s.

Now the program bounces off of the black and starts working leftwards along the bottom. Push operations of 3 and 2 and then a roll to bury the 2 100s under a 5. Next is push 1, subtract, and add to get 100+5-1=104 on top of the stack, which is unicode "h". Next 2 operations are push 1 and pointer to get around the corner and start moving right along the middle, and then output to print "h".

Next is add 100+5=105 on top of the stack, and output to print "i". The stack now contains two 5s. Push 1, add, multiply gives (1+5)*5=30. Finally push 3 and add for 33, and output for the trailing "!". The program then goes right through the remaining white space to end in the green on the right.

\$\begingroup\$Hah yes, was waiting for this :)\$\endgroup\$
– Sp3000Jan 20 '15 at 3:09

\$\begingroup\$How's that any different from a 2D character language? It's just the way you convey the cell values.\$\endgroup\$
– JDługoszJan 20 '15 at 3:31

25

\$\begingroup\$@jdlugosz Many esoteric programming languages, when you get down to it, are just a few basic stack manipulation commands with a unique way of encoding the commands. I personally think encoding them in an image is a neat idea.\$\endgroup\$
– SpencerJan 20 '15 at 4:00

13

\$\begingroup\$If we're talking functional equivalence, you could ask "How's that any different from a Turing machine?" but then you could level that same question at a cat, or the planet Jupiter, or any of the other languages...\$\endgroup\$
– trichoplaxJan 20 '15 at 5:37

(Note: Some snippets build on previous snippets, so unlike most answers I've decided to put them from earliest to latest.)

Factoid:

Like Befunge, ><> is a stack-based 2D language. This means that instructions aren't executed linearly like most traditional languages — program flow can be up, down, left or right!

Length 1 snippet:

X

X is an invalid command in ><>, so the error message something smells fishy... is printed. In fact, this is the only error message in ><>, whether the cause be division by zero or trying to pop an empty stack.

Length 2 snippet:

1n

Program flow in ><> starts from the top left and is initially rightward. 1 pushes a 1 onto the stack, then n prints it as a number (as opposed to as an ASCII char). But ><> programs are toroidal, meaning that the instruction pointer wraps around when it reaches the end of a line. So after the n we wrap to beginning, push a 1, print, wrap to the beginning, push a 1, print ... and we end up printing 1s forever!

Length 3 snippet:

"o;

Here " is string parsing, o outputs as an ASCII char and ; terminates the program. But what does the program actually do as a whole?

Well first we start string parsing, pushing every char we see onto the stack until we find a closing ". We push an o, then a ; ... and wrap the instruction pointer back to the start. But now we're on a " so we stop string parsing, and finally we execute the o and ; as normal to print the top of the stack (the ;) and terminate.

Yes, we've just used the same quote char to start and end a string!

Length 4 snippet:

42n;

Based on what we've seen so far, you might expect this to push 42, output as a number then terminate. But all instructions in ><> are single chars, so this actually pushes a 4 and a 2, then outputs the top of the stack as a number (only the 2) and terminates.

Length 5 snippet:

<v
;>

Remember, ><> is a 2D language. This means that there's got to be ways to change the direction of program flow!

Like Befunge, one way you can do this is via the arrows >^v<. To illustrate how they work, let's look at the above program:

Program flow is initially rightward

< makes program flow leftward — we go off the left and wrap around to the v

v makes program flow downward — we go down to the >

> makes program flow rightward — we go off the right and wrap around to the ;

Finally, we terminate.

Length 6 snippet:

";"00p

Another cool feature of ><> is that it's reflexive — the program can modify its own source code on the fly!

Here we push a ;, followed by two zeroes. p then pops the top three elements y, x, v (y being the top of the stack) and places v at the position x,y. In other words, the p in this program puts a semicolon at the position 0,0, turning the code into ;;"00p. This then allows the program to terminate, as the instruction pointer now wraps around and executes the newly-placed ;.

Length 7 snippet:

\7*n;
6

Unlike Befunge, ><> also has mirrors (\/|_#) which reflect the direction of program flow. So here we:

Start rightward, but the \ reflects us downward

Push a 6 and wrap

Hit the backside of the \ and reflect back to rightward

Push a 7

Multiply the top two of the stack

Output and terminate

Moving horizontally through a _ mirror or vertically through a | mirror is a no-op.

Length 8 snippet:

"r00g>o<

Quite possibly the simplest ><> quine if an error is allowed to be thrown. The two new instructions here are:

r: Reverse the stack

g: Get — pop y,x and push the character at x,y onto the stack (counterpart to p)

Using the string wrapping trick from before, the program initially pushes r00g>o< then hits the first quote again. The stack is then reversed, giving <o>g00r. After that we push the char at 0,0, the ", to give <o>g00r". Finally, we trap an o between two arrows, outputting the top of the stack until there's nothing left and we get an error.

Length 9 snippet:

x0\>
\1n>

x (lower case) moves the instruction pointer in a random direction, and the program showcases this functionality by printing random bits forever. Try following the arrows and mirrors to figure out how this works! (Don't forget to check all four directions, including up and left)

Length 10 snippet:

;a comment

There's no comment syntax in ><> — it doesn't need one. Just write what you want anywhere and make sure it doesn't get executed as code!

Length 11 snippet:

1!X2!X+!Xn;

! is a trampoline which skips over instructions. It's particularly useful when used with ?, a conditional trampoline which pops the top of the stack and executes the next instruction if the popped element is nonzero. We'll see how this works later.

The above code prints 3 by skipping over the Xs, only executing 1! 2! +! n;.

Length 12 snippet:

01v
ao>:@+:n

Prints the Fibonacci numbers forever starting from the second 1, one on each line. The new commands are:

A "tac" program which reads in a line of input and outputs it reversed. Thanks to @tomsmeding for the snippet.

= pops the top two elements and pushes 1 if they're equal, 0 otherwise. The first line keeps reading in input until ASCII char 13 (carriage return) is found, at which point it moves to the second line.

The l?!;o loop is an important construct in ><> which outputs the entire stack. Unlike >o<, it doesn't cause any errors. This is how it works:

l pushes the length of the stack

We check the length with ?:

If the length was nonzero, then the next instruction ! is executed, skipping the ;

If the length was zero, then we don't execute ! and terminate due to the ;

Note that no output actually happens until you hit carriage return.

Length 14 snippet:

32.
X67*n;

In addition to changing the direction of program flow, you can actually move the instruction pointer anywhere you like!

. pops y,x and teleports the instruction pointer to x,y, maintaining direction. Note, however, that you need to move to one square before where you want to go — the instruction pointer is updated before the next instruction is executed. So here the instruction pointer lands on the invalid X, but all is okay since the pointer moves to the 6 before continuing execution.

. makes it possible to convert most ><> programs into a one-liner, but why would you want to lose the fun of 2D? :)

Length 15 snippet:

01+:aa*=?;:nao!

Prints the numbers 0 to 99, one on each line. This program demonstrates a neat use of the ! trampoline — to ensure that the initial 0 is only pushed once.

Length 16 snippet:

"r00g!;oooooooo|

A proper quine which doesn't throw errors, inspired by the quine on the esolang page.

If you wondered about how to modify the previous quine (snippet #8) so that it wouldn't cause an error and thought "why don't I just add a ton of o instructions?", then you might realise that for every o you add, you need to output another o! This quine neatly solves the problem by putting a | mirror at the end, which allows each o to be used twice.

If we switch to single quotes (which are also for string parsing), then an alternative quine which doesn't use g is

'r3d*!;oooooooo|

Length 17 snippet:

b2,63,.
17,n;

We have addition (+), subtraction (-), multiplication (*), modulo (%)... but what about division? It's there, but since / is already a mirror, division has been assigned the , symbol instead. Interestingly, division is float division, not integer division!

The above program explores some undefined behaviour by trying to jump to 11/2, 6/3. The Python intepreter seems okay if the first coordinate is not an integer (although it jumps to the wrong spot), but chokes if the second isn't.

Length 18 snippet:

123456${{$}nnnnnn;

We've seen r which reverses the stack and @ which rotates the top three elements. Here are a few more commands which move elements on the stack:

Note that simply pushing reward and then outputting it again with oooooo would print drawer, due to the "first in, last out" nature of stacks.

Length 20 snippet:

aa*5+\
7a*2+\
oo; \

A little known feature of ><> is that, like Python, backslashes can be used for line continuation in many cases.*

The above code is functionally the same as

aa*5+7a*2+oo;

*Disclaimer: The reason why this works may or may not be for a completely different reason

Length 22 snippet:

1&fv ;n&<
&1->:0=?^:&*

In addition to stacks, ><> also has registers (one for each stack) which can be used to store values. Calling & for the first time moves the top value of the stack to the register, and executing & again moves the value back. This can be very useful when accumulating a value, for example sums and factorials.

The program above calculates the factorial of f (15), printing 1307674368000. Here's the trace for f replaced with 4:

Length 24 snippet:

"Hello, World!"rl?!;of0.

We have enough chars for everybody's favourite program! Here we use the . teleporter for the output loop.

Length 25 snippet:

0i:0(?v$a*$"0"-+!
;n~<

Unfortunately ><> only allows reading from STDIN one char at a time, which makes reading in numbers a little tricky. For input consisting of digits 0-9, this program is essentially atoi, converting a string of digits from STDIN into a number on the stack (which is then printed).

Another note is that on EOF, i pushes -1 onto the stack. This makes checking for EOF easy by comparing to 0 using (, or "less than".

This snippet also uses ~, which pops and discards the top element of the stack.

Length 33 snippet:

i>:nao:1=?;\
^ ,2v?%2:/
^+1*3<

Up until now, most snippets have either been relatively linear, or were just simple examples demonstrating ><>'s functionality. Now I can give an example which highlights how easy it is to visualise program flow in ><> with a well-laid-out program.

The program reads in a single ASCII character and runs the 3x+1 algorithm on its code point (In ><>, characters are basically integers). Each step of the algorithm is printed until we hit 1.

Here is a trace for the first few iterations with input a (code point 97):

Length 44 snippet:

a&>i:0(?v"+"$\
/&^?=0l< "a*"/
\:1+&2p/\0
n
;

I don't feel like I've done the p command justice, having only used it once all the way back in snippet #6, so here's a different atoi function. What's cool about this one? The program writes the expression needed to calculate the number as it reads the input!

So for input like 573, after all chars are read the end of the third line will look like \0a*5+a*7+a*3+, which evaluates to 573!

If you've managed to get down to here, then you might agree with me when I say that this is one very readable ROT13 program. Given a char c1, we find the first char c2 in AN[an{, such that c1 < c2, then apply the appropriate offset by adding/subtracting d (13). Note that [ and { are the chars directly after Z and z respectively.

Try it in the console, and watch the letters transform as you type!

(You can also pipe in the input, but as I'm missing the EOF check :0(?; it'll stop with an error when it tries to print -1 as a char)

Thanks for the votes! When compared to other languages and what they can do in limited bytes, C looks obsolete, fussy and too dependent on the developer. In many ways it is: scripted and higher level languages with automatic memory management are much more expressive and quicker to production than C will ever be.

So why feature C?

The hidden secret behind all those scripting languages is that the interpreters are likely written in C (or more recently, C++ or Java). The first C++ compilers actually compiled to C code. In fact, until there's a market for a direct compiler, it's usually more cost effective to write a compiler to generate C, and then compile that.

If you're working on very small platforms, maybe even without an operating system available, you're likely working in C. These days, just about every appliance has a microcontroller embedded in it, no doubt programmed in C. When they need it small and fast, C is the way to go. (Also FORTH, for the masochists.)

Knowing C takes you as close to the metal as you can go without getting into assembler, and helps you in other languages. You have a good idea how a C++ virtual function probably works. You know when you write those pass-by-value recursive functions in PHP, that internally it's doing a lot of memory allocation and copying, so you instinctively try out pass-by-reference. Callbacks and references don't freak out C developers, maybe Haskell does though.

As Kernighan and Ritchie mentioned in their preface of the classic C Programming Language, 2nd edition, C is not a big language, and it is not well served by a big book. I'm trying to follow this advice: examples do double, triple or more duty if possible.

All the snippets are at least compilable on their own. Those that are linkable and executable are indicated as such. I know this isn't a requirement, but it makes it simpler than trying to explain the framework required to make any code snippet work.

I also tried to make sure each code snippet was as short as possible so that I'm not introducing extra spaces just to pad to a certain length. In cases where code is indented, the indents are not included in the length, just one character for each new line.

C makes a distinction between compiling and linking. Many entities in C are just compiled and linked later - an example are all the static and dynamic libraries.

Other entities are just included and generate no code by themselves.

The above semi-colon will certainly compile into object code, and do nothing!

Length 2 snippet

x;

C, being an older programming language, has gone through several iterations. The earliest in widespread use was developed by Kernighan and Ritchie and abbreviated K&R. K&R C is notable for making a lot of assumptions about your code if you don't explicitly provide them.

In particular, in K&R C, the code above is assumed to be a global integer x initialized to 0. Compiling it in K&R mode will produce an object file which provides any program linking to it this variable for its use.

Length 3 snippet

??/

C is so widespread that it needs to provide compatibility features for systems which do not have all the characters it uses. The above is a trigraph for the backslash, which is used in C as a line continuation character. The above will compile, likely with a warning that there isn't a line following.

A common culture in C is to ignore compilation warnings, and many large code bases invariably have a few or more warnings when they're being built.

Length 4 snippet

f();

Again with K&R, the above is "filled out" to mean upon compilation that "There exists, with global linkage, a function f, to be provided later, which takes a fixed but unspecified number of arguments and returns an integer."

Note the fundamental differences between this and f;.

Length 5 snippet

s="";

K&R C is notable for being truly forgiving. Upon compilation, this code will provide an integer s for global linkage which is initialized to the starting address of an empty string (I think). K&R quietly handles all the coercions, including truncation if an integer isn't large enough to hold the address.

It is constructs like these which have generated many difficult-to-find bugs and provided much inspiration in IOCCC competitions.

Length 6 snippet

o=042;

A gotcha of even old timers, a leading 0 in a literal number means the digits following are in the octal base. The above code, upon compilation, will provide an integer o for global linkage initialized to decimal 34.

This feature of C has bitten many developers striving to pad their numbers to make them line up nice and even!

Length 7 snippet

f(){f;}

The above code is a function with a body. But what does it do? It retrieves the address of the function, and does nothing with it! Typically what the function will return is undefined. Nonsensical code like this can often compile without warning.

Length 8 snippet

main(){}

This represent the shortest compilable and linkable code in C. While in modern versions of C, functions usually cannot be defined implicitly, for historical reasons this restriction is relaxed for main.

This marvel of a program, which does nothing but return 0, will compile to non-negligible size, and link in various C runtime routines. You can compile and link with verbosity set to full to see what is going on under the hood.

Length 9 snippet

#define Z

A mainstay of C header files is the #define preprocessor directive. C programs compile in various stages, and in one of these stages these definitions are substituted with their actual values.

When an argument is missing, C will imply 1, so the above would substitute 1 wherever Z is used in the source code.

The above would typically be put into a header file and #included as required.

Length 10 snippet

enum{P,Q};

The enum keyword provides a sometimes type-safe way to define a series of constants. Like defines, they are often used in header files. The above code when included would define P as an integer of 0 and Q of 1.

Length 11 snippet

volatile v;

The volatile keyword is to let the compiler know that a variable may be changed by other agents and not to make assumptions that it will remain constant between accesses.

Length 12 snippet

#pragma once

#pragma once is a non-standard but widely supported preprocessor directive to indicate that the current source file be included only once in a single compilation.

The traditional and fully supported technique is to use #include guards with the disadvantages of added code and possible name clashes.

Length 13 snippet

w(){for(;;);}

There are numerous conventions in C, and one of these is how to represent infinite loops. In this case, for(;;) indicates no initialization, no exit check which defaults to 1 meaning true - i.e. don't break, and no looping code.

Sometime it's possible to do everything inside of the () and the loop itself needs no body. In this case a dummy semicolon is added at the end.

In the code above, when compiled, it will provide a function which will enter a tight busy loop - one of the no-no's in software design - and never return.

Length 14 snippet

int a[]={1,2};

Arrays in C do not need the lengths specified. The empty square brackets [] tell the compiler to "figure it out yourself". However in C, unlike other languages, there isn't a built-in way to prevent accessing an array outside of these bounds, leading to the "shoot yourself in the foot" metaphor that C is known for.

The code above, when compiled, will provide a global mutable array a of two integers initialized with 1 and 2.

Length 15 snippet

const long k=7;

The const specifer is a later addition to C borrowed from C++. A common interview question is "Does it make sense to define a variable as volatile const?". const along with enum and inline are intended to reduce the reliance on #define which has issues with type safety.

Length 16 snippet

extern void **q;

extern is used to indicate that a variable is declared elsewhere. The void * type is the standard generic type in C, meaning it doesn't need to be explicitly cast to or cast from in assignment statements. The ** operator sequence means pointer to a pointer, which often blows the minds of newbies, but is perfectly valid and often used C.

Length 17 snippet

double d=4/3-1/3;

If you were to print the above, the result would be one, and you'd think, super! Change to double d=4/3-2/3; and what's the answer? It's still one! C is using integer arithmetic to calculate 4/3 → 1 and 2/3 → 0, and 1 - 0 → 1!

Length 18 snippet

main(){puts("!");}

Finally we get to some code that actually does something! puts is a favorite of C golfers because it doesn't require a header file to use.

puts will also add a line feed to the output. Conversely, its counterpart gets will strip line feeds. One should never use gets except in very controlled circumstances - it has no protection for buffer overruns and is the root cause of many exploits.

Length 19 snippet

#include <stdlib.h>

The inclusion of header files is often a personal signature of developers. Many include lib and io regardless if they are needed. Some order the header files so the lengths are increasing or decreasing. Most put <> before "". Personally I have used this signature in my TA days to check for cheating among students: same header signature? take a closer look!

Length 20 snippet

char*p=(char*)0x300;

C is designed to be used on very low level rudimentary platforms. In some cases you might need to access special memory mapped ports directly.

In the code above the address of a port is defined as hexadecimal 300. You would access the value of the port by using *p, as in *p=0xff; to turn all bits on, or v=*p; to retrieve the current value.

Length 21 snippet

int w=sizeof(double);

The sizeof operator provides the size in bytes of a type. With variable names the brackets aren't required e.g. double d;int w=sizeof d;.

Length 22 snippet

asm("xorl %ecx,%ecx");

How asm is to be used is defined by the compiler. The above is an example of Linux gcc in-line code on an Intel platform.

The original Unix had a small but non-negligible fraction of its code in assembler. Even today, if speed is of primary concern and portability absolutely isn't, you'll see it used.

On compatible systems, the code above will compile, and it will be literally an isolated assembly instruction with no conventional means of accessing it! BTW xor R,R is a common assembly language idiom for clearing a register quickly.

Length 23 snippet

union u{char c;int i;};

A union will provide at least enough space for the largest element. You might see it used in conjunction with void * to provide a common "opaque" type in certain libraries. In this case, the union will usually be part of larger structure, with the structure having a field to identify the union type.

Length 24 snippet

/*INTS*/int i,j,k;//INTS

The original C comment was delimited as /* comment */, and borrowed the // comment to end of line format from C++.

Length 25 snippet

int main(void){return 1;}

This is the more compliant version of the length 8 snippet above. The return type and function types are specified, and it has an explicitly returned value.

The convention in C is to use a return value of 0 for success and 1 for failure, or if you want to be strictly conformant EXIT_SUCCESS and EXIT_FAILURE as defined in stdlib.h.

Length 26 snippet

typedef struct{int x,y;}P;

typedef is extremely useful, in particular, typedef struct. In modern terms you might call it "object-orientation-light".

After including the above, the code can use P as a regular type in declarations and functions, with full type-checking. Unlike C++ though, you can't define operators like +,*, or <<, hence "object-orientation-light".

C can explicitly define bit-fields which can be assigned and read and manipulated like any integer.

The above is an approximation of an IEEE single-width floating point data structure.

Length 36 snippet

f(unsigned x){return!!x&!(x&(x-1));}

In many languages, you don't need to care about how numbers are represented. In C, you need to be intimately aware of their internal representation.

The best example of this I can think of is determining if an integer is a power of two {1, 2, 4, 8, ...}. Those not familiar with C will do loops and shifts and all manner of stuff for O(log(n)) run-time, not bad, but above is a function which will do the same in O(1) run-time. I'll leave it as an exercise for the reader to confirm it works, but it really does...

The !! convention is often used to coerce an integer from non-zero and zero to 1 and 0 respectively. Many C developers like to use these kinds of tricks (often at odds of those who value code clarity).

Super keen C developers can confirm that the above will work on ones-complement and signed hardware. For those wondering, you're almost certain to be working on twos-complement hardware right now. Only the really lucky (or unlucky depending on your perspective) need to worry about this!

Length 48 snippet

#include<complex.h>
double complex c=3.0+I*4.0;

C99 includes support for complex numbers. As you can see from the code, it takes the form of a modifier for a real type. You could also use int complex c=3+I*4; but internally it coerces to a floating point type. The above code will compile in gcc using gcc -std=c99 -c length-48.c.

If you want to see more of the internals, try compiling with the -E switch. For my version of gcc, the declaration above becomes double _Complex c=3.0+(__extension__ 1.0iF)*4.0;. Note that the complex type is a significant addition to the language, not just a few cheap macros.

This is just a teaser, when we get to more than 125 characters, then we can start having some real fun with complex numbers!

Length 51 snippet

#include <math.h>
main(){double d=sqrt(sin(3.2));}

For various reasons, C doesn't automatically link to the standard mathematical functions such as sin, cos, tan, sqrt, etc. So if they're used, but not linked, the developer will be presented with the linker error undefined reference to 'sqrt', or some other error.

In gcc, the code above will compile and link using gcc length-51.c -lm.

Note sin(3.2) will return a negative number, of which the square root is not legal in the real domain. In C, a special value NaN is returned to indicate this error, which the program is free to ignore!

In C99, there are a lot of new exception handling functions to provide very safe and fine-grained control of these kinds of math errors, which just about nobody uses!

Length 63 snippet

static int w;static int X(int x){static int s=0;s^=x;return s;}

Or formatted more sanely:

static int w;
static int X(int x)
{
static int s=7;
s^=x;
return s;
}

As you might have guessed, this is all about the keyword static which has more than one meaning in C.

In the first two cases, static is telling the compiler that integer w and function X are not visible outside of this file or compilation unit, i.e. they are internal.

These functions are not intended to be called externally, so they might not check the arguments for validity, and cut other corners. Because they have internal scope, you can redefine w and X in other files, and they will usually be separate.

In the last case, static indicates that the integer s retains its value between function calls. The first time X is called, s will be its initial value 7, when it is exclusive-ORed with x, the new value will be retained.

Internally, although it is implementation dependent, the usual memory organization is that s is residing on the heap, specifically initialized memory, while the argument x is residing on the stack. Where variables reside is important if you want to implement recursive algorithms, for example.

A gotcha in C are clashes with global variables. Until w and X are actually defined as static, if they are defined globally somewhere, then w and X will refer to the global entities instead.

Here q and w may not be initialized to the same value, because a global w is being used to set q:

static int q = w;
static int w;

If a global w doesn't exist, the compilation should fail.

Here q and w will be initialized to the same value:

static int w;
static int q = w;

Typically, designers will reduce name clashes by adding a distinctive prefix or suffix to their global variables and functions.

In C99, static has gained another use, e.g. int Y(int a[static 10]); which means that there is a function Y which takes an array of at least 10 integers.

The keyword register provides a hint to the compiler that using hardware registers would be beneficial here. The above function will copy l integers from q to p, using hardware registers if possible.

Sometimes the speedups could be significant. For example, in the 68K microprocessor family, the line *p++ = *q++ could be translated to a single instruction MOVE.W (Ap)+,(Aq)+ vs. six or eight if you didn't use register. The 68K microprocessor had explicit post-increment and pre-decrement modes, so the savvy developer, if he knew the platform, would tailor code by using x++ and --y vs. ++x and y--.

These days compilers mostly ignore register, other than not allowing addresses to be taken of them (e.g. in the above &l would cause a compiler error).

Ah, recursion! The snippet is a complete program to compile, link and run. The function f calculates the factorial of its argument x by using the recursive formula f(x) = x * f(x - 1). Factorials get big really quickly, so for example f(12) is the largest value you can get in a signed 32-bit integer.

For an example of really recursive code, look into naïve implementations of the Ackermann function.

Smart compilers can optimize the function, using the hint inline and "unroll" the function when constants are provided as arguments so that:

f(12)

Becomes:

12 * 11 * 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

Without any function calls required!

Other compilers can reorganize the function:

int f(int x)
{
return (x < 2)? 1: f(x - 1);
}

And implement something called tail-recursion. This in effect replaces the last function call to a simple goto and lets that function deal with the return. The benefit is less stack thrashing, faster and smaller code.

In assembly language, these kinds of optimizing opportunities are really easy to spot and can be implemented by something called a "keyhole optimizer", which basically looks for small patterns and replaces them with something faster and/or smaller.

C borrowed from languages contemporary at the time, the concept of a universal I/O which could be consistently applied to any device, whether console, punch card, tape, disc or printer, but in true C form, it allowed the developer to create very terse but powerful statements.

In the above snippet, it will take command line input, parse two integers separated by spaces, tabs or commas and output them. It takes advantage of a newer scanf specifier %*[\t ,] which will: [\t ,] pull out all tabs, spaces and commas, and: * ignore them.

I remember revising some C++ code where the developer was doing everything the "pure" C++ way with << and an arsenal of methods like find and substr. It was at least a dozen lines and it still couldn't handle commas as delimiters. I replaced all that clunky code with a single sscanf line like above!

Note the .5 limits the output for the specifier to at most five characters, while the leading 5 ensures the output is at least five characters, with - indicating left alignment. Combining them sets the output at exactly five characters.

x86 Machine Code

Factoid:

x86 Machine Code is the assembled version of x86 Assembly that the processor actually runs. It was developed back when memory and storage space were expensive, and was designed to be somewhat backwards compatible all the way to the Intel 8008. Keeping executable code small was one of the goals, and it utilizes variable length instructions and a CISC architecture to help achieve this (which has had the drawback of making it more complicated to improve performance on modern processors). This, along with the bare-bones nature of assembly and machine code in general, gives x86 programs the ability to be extremely compact.

Length 1:

Now for the first program:

0xC3

Open up a hex editor, enter that byte, and save it as test.com.

You now have valid MS-DOS program which immediately returns without doing anything, since 0xC3 is the instruction 'RET'. This does however show another interesting aspect for golfing with x86: the .com file format. This executable format has absolutely no header - the file is simply loaded into memory starting at address 0x100, and then execution is started at 0x100. This means no bytes wasted on metadata!

Length 2:

Our next program:

0x4D 0x5A

or 'MZ' in ASCII.

Ok, I cheated a bit, that really isn't a useful program, since it corresponds to the instructions

DEC BP
POP DX

Which aren't actually useful for starting a .com program. In fact, that's the whole point of those two values - no reasonable .com file should start with them! .com files were limited to 65280 bytes in size (64KiB - 0x100), so when larger programs started to be needed, a new format had to be developed. This was the .exe file format, which does have a header. However, MS-DOS needed to keep the .com extension on certain components for backwards compatibility, so it needed a way to detect whether a .com file was really an .exe. They chose the sting 'MZ' as this magic number, and to this day, if you open up a Windows .exe (or .dll) file in a hex editor, you'll see they start with those two bytes. It amuses me that even the most modern Windows program starts with a compatibility constraint from the 70's.

Length 3:

Now for an infinite loop:

41 E2 FD

Which translates to

start:
inc cx
loop start

This program increments the value of CX (which will be >0 to begin with), then executes the loop instruction. Loop is an excellent example of a CISC instruction since it combines 3 simple operations into one special-purpose operation: it decrements the value of CX, checks if it is 0, and jumps to the target label if not. There are also forms of loop that check other flags in addition to ending when CX is 0. We could have done just 'jump start' for a 2 byte infinite loop, but this was more interesting.

Length 4:

A program that is minimally useful:

40 CD 10 C3

Translated to assembly:

inc ax ; 1 byte
int 10h ; 2 bytes
ret ; 1 byte

This program sets the console to 40x25 characters, clears the screen, then returns to the command line. AX is set to the video mode we want (1), then the BIOS interrupt 10h is called to actually set the video mode & clear the window, before returning. Expect to see more of these BIOS interrupts in the future.

Length 5:

We can now implement a pause program:

B4 01 CD 21 C3

Translated to assembly:

mov ah,1 ; 2 bytes
int 21h ; 2 bytes
ret ; 1 byte

This program tells the BIOS to wait for a key to be pressed and echos it to the screen before returning. This also demonstrates how on the x86, some of the registers can be partially read or written. In this case, we set the top byte of AX (AH) to 1. On 32 bit processors, you can also operate on the low 16 bits without affecting the top 16 bits. This ability to modify partial registers can be handy for assembly programmers, but has drawbacks for modern processors trying to perform out-of-order execution, since
they can introduce false data dependencies.

The output is the default character set repeated in different colors. The low byte of AX is the character code, and the high byte specifies the colors to use.

16 bit programs could only address up to 64KiB directly. To get around this, the x86 used 'segments' - special registers that would be multiplied by 16 and added to all memory accesses to give 20 bits of addressable memory. A program could change the values of these segment registers in order to access more memory - or special areas of memory: this program modifies the extra segment in order to write to video memory.
Different types of memory access used different segment registers, allowing code, data, and the stack to be accessible in different chunks of memory at the same time. The default segment could also be overridden for many instructions.

Length 20:

Let's make something recognizable - we will use 'Rule 90' to draw Sierpinski triangles.

For this program, we use the somewhat famous 'Mode 13' - a graphics mode that has a resolution of 320x200 with 256 colors. It was used by many popular DOS games, such as Doom.

Length 21

Let's see who manufactured the CPU we're running on.

0F A2 66 60 BB EE FF B9 0C 00 8A 17 43 B4 02 CD 21 E2 F7 FF E1

Translated to assembly:

cpuid ; 2b CPU ID - retrieve processor information based on the value in AX. For AX=0,
; the 12 bytes in EBX, ECX, and EDX are loaded with a vendor identification string
pushad ; 2b Push all registers on the stack (32 bit version)
mov bx,0xffee; 3b Start of the vendor identification string on the stack
mov cx,12 ; 3b 12 characters to print
print:
mov dl,[bx] ; 2b Character to print
inc bx ; 1b Advance string position
mov ah,2 ; 2b Set AH to the 'Print character to STDOUT' value
int 21h ; 2b Call the bios interrupt to print
loop print ; 2b Decrement CX and jump if it is not zero
jmp cx ; 2b Instead of restoring the stack, just jump right to the exit point

Sample output:

c:\misc>cpuid.com
GenuineIntel

This program uses the CPUID instruction to get info about the processor it is running on, in particular, the vendor identification string. Most people will see 'GenuineIntel' or 'AuthenticAMD', unless they have an uncommon CPU manufacturer or are running in certain virtual machines.

This program uses the midi card to turn the keyboard into a piano. To do this, the midi card is set to UART mode, which plays midi notes as soon as they are received. Next, the program waits for a character to be pressed, and outputs the ASCII value as a note to the midi card. The program runs until escape is pressed.

mov bl,7 ;Counter for the total number of constants to print
start:
fld1 ;Floating point constant to load on the FP stack,
;start with 1 since it's op-code is the lowest
mov cl,17 ;Multiply the constant by 10, 17 times to get the
mult: ;printing part as an integer
fimul word[ten]
loop mult
mov si,10+'$'*256;ASCII new line (10) and the end-of-string ($)
;characters. These are used both as
push si ;a constant memory location, and stored to the
;stack to format and printing
mov cl,9 ;print 18 digits (9 pairs)
fbstp [si] ;store the integer part of the floating point
;number on top of the FP stack as a packed
;binary-coded decimal number (1 digit/nibble),
;and then pop the number off the FP stack
convert:
lodsb ;load a pair of packed digits
db 0xd4,16 ; AAM 16 ;ASCII Adjust For Multiply instruction using
;non-standard base 16. This puts AL/16 in AH,
;and AL%16 in AL, unpacking the digit pair.
xchg ah,al ;Swap the digit order
add ax,'00' ;Convert the digits to ASCII values
push ax ;Store digits on the stack
loop convert
inc sp ;AX now holds the 1st 2 digits to print,
mov ah,'.' ;so to insert a decimal point, the 2nd digit
push ax ;is replaced with a '.', the stack pointer
;is adjusted to overwrite 1 byte, and then
;AX is pushed on the stack
mov dx,sp ;Load DX with the start of the print string
mov ah,9 ;Load AH with the 'Print String' constant
int 21h ;Call the 'Print String' interrupt to display
;the constant
inc byte[start+1];Self-modifying code - increment the load
;floating point constant op-code to iterate
;through all of them
dec bx
jnz start ;Exit when all 7 constants have been printed
int 20h
ten: dw 10

Floating point math on x86 systems was originally handled by the optional x87 co-processor, it wasn't until the 486 that it was moved onto the same chip. The x87 also had a rather different architecture, it was stack-based, with 8 80bit registers available. It also had a variety of rounding modes, precision, and maskable exceptions that could be set.

This program prints the values for seven constants baked into the processors. It may seem odd that instruction space would be wasted on simple constants like 0 and 1, but keep in mind that the instruction set was created when memory was small, and these instructions are typically 2 bytes smaller than equivalent operations. The program also uses an obscure instruction, FBSTP -'Store BCD Integer and Pop'. Back when the x86 was developed, operations on BCD numbers were more common, and the x86/x87 has several instructions specifically to simplify BCD math, such as the AAM 'ASCII Adjust for Multiple' instruction also used in the program.

In the unprotected memory model used by early x86 programs, there is no distinction between data and code. Because of this, it is easy to iterate through the sequentially encoded 'Load Constant' instructions by simply incrementing the appropriate value.

Length 64

Cross-posting my entry for the Mandelbrot Challenge, a program can be written that displays a 320x200 color Mandelbrot fractal in only 64 bytes.

This program uses fixed-point math to generate the fractal, since it takes fewer bytes. The lowest 6 bits of the 16 bit registers is considered to be the fractional part of the number, and the values are rescaled after being multiplied.

Haskell

You might want to read from the bottom up. Sometimes I refer back to lower snippets, but never to higher ones, so it might help understanding.

Readers who do not know Haskell: am I clear? When am I not clear? I can't tell.

Length 86 snippet

A foldable instance for our tree data structure (snippet 23).
Foldable is a type class - as in, a class(/group) of types. These are parallel to interfaces in Java. They essentially generalize over types, unifying types which have common characteristics; for example, they can be added together (Monoid), containers (Functor), can be printed as text (Show, which we have met already, in the show function), and so on.
This one unifies data types which are list-like in that they can be iterated over or flattened to a list.

In this snippet, we define the instance by defining foldr, which essentially iterates over the data type from right to left. Now, we can use a bunch of general pre-written code. First, we define a helper function to get a singleton tree, to avoid all the clutter: s a = N E a E. Now:

Length 70 snippet

primes=sieve[2..] where
sieve(p:xs)=p:sieve(filter(\x->x`mod`p/=0)xs)

This is a prime sieve!

(note: /= is what != is in other languages)

This works by defining a function sieve which filters the list and keeps only the numbers which are not divisible by any previous prime. It is defined recursively - to sieve is defined as to split the list to a first element p and a tail, filter from the tail any number divisible by p, sieve the remaining bit, attach p to the start of that, and return.

Again, we are working with infinite lists here - but the computation will halt in time as long as you don't require an infinite amount of primes to be computed.

take 4 primes === [2,3,5,7]

Length 68 snippet

Finally, a quine!

main=do putStr s;print s where s="main=do putStr s;print s where s="

In your first time reading this, you might think that the output of this quine would be missing the quotation marks, and why would you once write putStr and once print? It sounds the same.

In Haskell, putStr is a function that just prints the contents of the string it gets to stdout; print, though, prints things to stdout.
So, print 4 is equivalent to putStr "4\n", but putStr 4 is nonsensical - 4 is not a string!
So, when print gets a value, it first converts it into a string, and then prints that string. Generally the way to convert things to strings is to find the way you would write it down in code. So, the way you would write the string abc in a string in Haskell code is "abc", so print "abc" actually prints "abc", not abc.

How fortunate I have enough votes now, I won't have to golf these things

Length 33 snippet:

main=go 0
go n=do print n;go(n+1)

The important thing to note is that we didn't use a loop. Haskell doesn't loop. Haskell recurses. Haskell doesn't have loops. It's deeper than that: Haskell doesn't even have Control flow.
How, you might ask? Well, it doesn't need any.

On with the details.
This program prints an infinite increasing sequence of integers, starting from 0.
go prints them starting with its input, then main calls it on 0.

do is a special syntactic power of Haskell. In this scenario, it just combines I/O actions, just like >> does (see snippet 22).

Length 26 snippet:

map f=foldr(\x y->f x:y)[]

This defines the map function, probably familiar to everyone, using foldr.
Notice that although we didn't declare map's type, the computer somehow knows its type is (a -> b) -> [a] -> [b], i.e. given a function from a to b, and a list of as, return a list of bs.

How did it know?? ;-)

Length 25 snippet:

main=putStr"Hello World"

The standard Hello World. Note the types: main has type of IO () and putStr has type of String -> IO () (a function from strings to I/O actions which return nothing).

Length 23 snippet:

data T a=E|N(T a)a(T a)

This is a standard definition of a Tree. How much easier than all those lines required to define a tree in Java, C, or anything else.

(see snippet 10)

Let's break it down:

data - this declaration declares a data type.
T a - a tree containing elements of type a. This is the type we are defining.
= - every value of T a will be any of the following, separated by a pipe |.
E - one of the possible values of T s - the empty tree.
N (T a) a (T a) - the other possible value of a tree - a node. Each node consists of the left child ((T a)) the element (a) and the right child ((T a)).

Length 22 snippet:

main=putStrLn"y">>main

A Haskell yes function.
>> is an operator which combines and sequences two I/O actions. It has type of >> :: IO a -> IO b -> IO b.

main is defined recursively by itself, as the I/O action which first prints "y" and then does whatever main itself does.

Length 18 snippet:

fix f=r where r=f r

A better definition for fix. (See snippet 14.)
The problem with the first definition, fix f = f(fix f), is that every time we call fix ffix recalls fix f, which recalls fix f, generating endless copies of the same computation. This version fixes it by defining r (result) to be the result; as such, f r = r. So, let's define r = f r. Now we return r.

Length 15 snippet:

sum=foldl (+) 0

This defines the sum function using a fold. A fold is basically a loop over the elements of a list with one accumulator.foldl takes as arguments some function f and some initial value x for the accumulator and a list xs. The function f should get as input the previous accumulator value and the current value of the list, and it returns the next accumulator.
Then the fold iterates on the list values, applying f on the previous accumulator, and then returns the last accumulator.

Another way to think about folds is like the fold 'inserts' f between the list values and with the initial accumulator in one of the sides. For example, foldl (*) 1 [4,2,5] evaluates to 1 * 4 * 2 * 5.

Length 14 snippet:

fix f=f(fix f)

The y combinator. It is usually named fix because it finds the fixpoint of the equation f x = x. Note that x = infinite loop can also sometimes a solution, so fix (\x -> x^2 + 5*x + 7) won't solve the equation x^2 + 4*x + 7 = 0 but instead return an infinite loop.

You may also note that not always x = infinite loop is a solution, because of Haskell's laziness.

This version is a time and space leak; we will redefine it in a longer snippet.

Length 13 snippet:

f=sum.map(^2)

This defines the functionf that given a list returns the sum of its squares. It is the function composition of the functionsum and the functionmap(^2), which in turn is the functionmap applied to the function(^2) (the squarefunction), which is in turn a section of the function^ (sections were introduced at snippet 2, and composition at snippet 3).

As you can see, functions are quite important in a functional language like Haskell. In fact, it has been said that Haskell is the language with the most standard library functions which get functions as inputs or return functions as outputs (this is commonly known as a higher-order function.

By the way, technically, every two-or-more argument function is a function which returns functions as outputs (this is called currying).

Length 10 snippet:

data B=T|F

This is a definition of Haskell booleans with different names. The boolean type is named B. This definition introduces two constructors: true (T) and false (F).
This code snippet basically tells the compiler that every boolean (B) is either true (T) or false (F), or in other words, B=T|F.

In fact, all data types ever can be defined in Haskell, when in other languages the number, references and array data types need special support from the compiler. In practice there is special support in Haskell as it would be very inconvenient otherwise, but for example the Bool datatype is defined entirely in language.

Length 9 snippet:

main=main

This nonsensical program will define main to be main. Because Haskell is lazy, values which would require an infinite loop to evaluate can be used freely if we don't use their actual value. Such values which contain infinite loops, like our main, are called "bottoms".

A fun fact is that the GHC Haskell compiler can detect these kinds of infinite loops and throw a catchable (!) exception when it is run.

Length 8 snippet:

f(x:_)=x

This defines the function f which, given a non-empty list, will return its head.

Patterns in Haskell are like Python's sequence unpacking, but generalized for all types. Patterns can either reject or match a value, and if it matches, can bind variables to values.

The patterns in this snippet are:

_: the pattern which matches anything and binds no variable.

x: the pattern which bind anything and binds it to the variable x.

:: this pattern gets to child patterns, that is, one for the head, and one for the tail. If the list is non empty, it matches them with the head and the tail.

Pattern matching is highly generalized. In fact, just defining new data types will automatically introduce patterns for working with them.

Length 5 snippet:

x=2:x

Whoa, there's so much to explain on this one.

First of all, Haskell is lazy. This means that subexpressions will be evaluated only when strictly necessary.

Note: this code snippet doesn't show assignment, but definition. Haskell doesn't have assignment.

This code snippet defined x, an infinite list made up entirely of 2. Usually in other languages x has to be evaluated before 2:x can ever be evaluated, but in Haskell we can do this.

Haskell infinite lists are sort of a mix of iterators and regular linked lists: they act like both (an iteration over a range will use constant memory, for example).

Length 4 snippet:

2:[]

This snippet just encodes the singleton list [2].
: is the Cons operator in Haskell. In fact, the regular list syntax is just syntactic sugar for the cons operator and the empty list literal. This tightly ties in into the way Haskell deals with Pattern matching and Data types (particularly the concept of constructor).

Length 3 snippet:

f.g

In Haskell, . stands for function composition. Haskell can be written in a "point-free" style, which is characterized by not naming function arguments and instead using the . operator to manipulate data flow.

Length 2 snippet:

1-

When this code is wrapped in parentheses (for syntactical reasons) it is called a "section". It is then a function that given some number, "fills up" the empty spot and returns one minus that number. This notion is sometimes useful in a functional language like Haskell, where otherwise a lambda would be needed.

Length 1 snippet:

1

In Haskell, 1 can be both an Int, Float, Double, Word and so forth. In fact, you can write code to define a version of 1 in any type and use it freely.
this is done too in JavaScript, Python and so forth, but unlike those, it is done with full type safety.

factoid:

Originally, the Haskell committee intended to call the language "Curry" after Haskell B. Curry's name but decided to change the name to Haskell because some puns might arise. Only later they noticed Haskell's similarity to "Pascal" and "Hassle"!

\$\begingroup\$i don't know if i should replace the factoid with the fact that Haskell has the most function/operators in it's standard library which generate functions from other functions (and that technically every two or more parameter function is such). should I?\$\endgroup\$
– proud haskellerJan 19 '15 at 13:49

\$\begingroup\$Show it off in a snippet and add it in the explanation.\$\endgroup\$
– Martin EnderJan 19 '15 at 14:12

\$\begingroup\$ugh i added a bunch of snippets and then my computer shut down\$\endgroup\$
– proud haskellerJan 20 '15 at 18:42

\$\begingroup\$@proudhaskeller Saving op. I've never done this personally, but if you have a large edit to do at once, you could perform the edit in an external document with saving, then paste it in when it's complete.\$\endgroup\$
– mbomb007Jan 20 '15 at 19:00

C#

C# is a fun, crazy mix of features from Java, C, Haskell, SQL, and a ton of other languages, and it provides a lot of really nice features and APIs. It's also known around here for being pretty verbose, but we'll see what we can do!

I'll ignore the usual required boilerplate:

class Program { public static void Main(string[] args) { ... } }

Length 1:

;

Commands are terminated with semicolons in C#! An empty line is perfectly valid syntax.

Length 5:

x=5f;

When you specify literal numbers in C#, the compiler will assume that they are ints or doubles (based on whether they have a decimal point). If you want to use a literal float, you should specify that by appending 'f' to the number, or it will be cast at runtime, incurring a slight cost.

Length 7 (bytes):

s=@"
";

If you prefix a string literal with an @ sign, it becomes a "verbatim" string literal. Normal string literals parse escape sequences like '\n' into special characters, but verbatim literals don't, allowing you to use the backslash character without escaping it. They can also include line returns, as shown. That could save you a few bytes in golf, or make your multi-line string literals more readable. Just watch out for indentation being included in the string.

Length 8:

()=>x=y;

This expression is an anonymous function. It returns an object of type Action that can be passed around and also called like a function. Anonymous functions inherit the scope in which they were declared, and they pull any local variables in that scope with them anywhere they go.

Length 9:

(a)=>a.p;

Here's another anonymous function that uses a parameter and return value. The expression returns an object of type Func (the Func itself returns the type of a.p. You'll use Func a lot to interface with Linq.

Length 10:

enm.Any();

This is our first introduction to Linq! Linq is a set of extension methods that can be called on any object that is enumerable (implementing the IEnumerable interface) - like Array and List. IEnumerable employs lazy evaluation: it goes through the collection one item at a time, without knowing about the collection as a whole - it could even be infinite!

That's where Any comes in - it returns true if the Enumerable contains at least 1 item. Much better than calculating out the whole length.

Length 11:

var a=1.5f;

The var keyword instructs the compiler to automatically determine the type of a. a in this case will be typed as Single. Very handy for code golf, as it's shorter by far than almost any type name, though many dislike using it in production code.

Length 15:

yield return 0;

Here's a crazy statement you may be less familiar with. You know that objects can be enumerable by inheriting IEnumerable, but did you know that functions can be enumerable? Declare a function with a return type of IEnumerable, and have it yield return as many times as you want. When you get an Enumerator to the function, each call to GetNext will have the program execute all the code up to the next yield return, return that value, and then pause until you advance it again. You use yield break to end the iteration.

Length 16:

[Obsolete]int a;

This snippet shows an attribute. An attribute is a kind of tag you can stick on any declaration in your code. Some instruct the compiler to do certain things, like this one that emits an Obsolete warning if you call a. You can create your own by extending Attribute, and you can query them using Reflection (more on that later, perhaps). You can go meta and restrict what kind of declarations an attribute can be used on with the AttributeUsage attribute.

Length 17

c.Count(t=>t==3);

Here's a handy golf method. Given a Func that maps an element of the enumerable c to bool, it returns the number of elements in c for which that Func returns true. Much nicer than writing out a loop.

Length 18:

foreach(T t in c);

This is a for-each loop. With all this talk of enumerable things, this is a much-needed structure. foreach is syntactic sugar that will set up an Enumerator for c (which must be enumerable) and iterate through it one element t at a time. You can alter or examine each individual element, but altering the collection itself will invalidate the enumerator.

Length 19

c.Select(t=>t.a/2);

This is your 'map' function, for functional programming fans. Select is a nice concise way to perform some arbitrary conversion (defined by a Func passed in) on each element of an enumerable. It returns an IEnumerable that will spit out the "converted" elements when you iterate it.

Length 21

Console.Write("Hi!");

This line writes some text to stdout, and is probably one of the main reasons C# isn't used for golfing much!

Length 23

typeof(T).GetMethods();

C# supports a very powerful feature called Reflection. Reflection lets you examine the structure of your code at runtime. For example, this call will return an Array of all methods on the specified type. You can examine those methods, call them, or even modify the values of fields and properties. Attributes (see Length 16) are a good way to tag parts of your code for use with Reflection.

Length 25

from t in c select t.a/2;

Is that SQL? In C# code? Pretty close. This expression does the same thing as the one at Length 19.

Length 27

for(var l;;l=new object());

C# is a garbage-collected language, which means that any memory you allocate (using the new keyword) can be automatically released as long as no references to it exist. This code will run happily forever even though I never explicitly free the memory created. Garbage collection has costs, though - search the web to learn more.

Length 29

var e=Enumerable.Range(0,99);

Enumerable.Range is a potentially handy golf function. It returns a structure that can be enumerated and will yield each number in the range specified, in order. The second parameter is a count, not an index.

Length 31

public int pr{get;private set;}

Here, we can show a simple 'property', an OOP feature and another hallmark of C#. If you've ever used Java, you've probably made 'get' and 'set' methods for a field in order to separate their accessibility or run code when it's changed. Well, C# lets you declare that code right on top of the field, and also set separate access modifiers for getting and setting. This particular snippet automatically creates a default getter and setter, but makes the setter private.

Length 32

public static void m(this T o){}

This snippet shows a C# feature that's nice for API design. By applying the this modifier to the first parameter of a static method, that method becomes an "extension" method. Once this is declared, T.m can now be called on any object of type T as though it were actually a method of T. This can be used to add new functionality to any existing class, without modifying or even having access to its source code.

Length 38

int f(int a,ref int b,out int c){c=0;}

This method showcases different types of parameter passing you can have in C#. Unmodified parameters are passed by value. Parameters prefixed by ref are passed by reference: you can assign a completely new object to them and they will carry it back out of the method. Parameters prefixed by out are like additional return values: you are required to assign them a value in the method, and they are carried back out just like ref parameters.

Length 42

Console.Write("It is \{DateTime.Now()}.");

The new C# 6 standard can save you some characters when you have to output assembled strings, using string interpolation. This feature allows you to write any expression in curly braces inside a string literal, and the string will be automatically assembled with the values of those expressions at runtime.

Length 48

IEnumerable f(){for(int a=0;;)yield return a++;}

Just enough characters now to do something with an actual purpose! This method uses some of ideas we explored above to create an infinite Enumerable that will simply return the integers, one-by-one, starting with 0. Remember that C# employs lazy evaluation with Enumerables, so an infinite sequence is perfectly valid - you can iterate as much of the sequence as you want, and break out at any time.

Length 56

int p{get{return mP;}set{mP=Math.Max(value,0);}};int mP;

Here is another example of a 'property' (see snippet 31). Here, I have actually defined different code snippets for get and set rather than using the automatic ones as before. This example demonstrates how you can use a property to validate the value assigned to a variable - here, the value is not allowed to become less than 0. Other good uses of properties include notifying an event when a value is changed, or rebuilding cached values that might be based on this one.

Length 65

int v;public static implicit operator int(Program o){return o.v;}

This feature is called an implicit cast. It's sort of like an extension method in that it is static code that operates on a specific class (see snippet 32). However, the implicit cast isn't used by calling it - it's used simply by treating a Program object as an integer (e.g. int i=new Program()). When you do this, the object will be silently converted into the type you're using it as, based on the code in the implicit cast. Best practice says to only do this when no information is lost as a result of the conversion.

Java

Length 44 snippet

Length 43 snippet

a contains 10 arrays which each contain 2 arrays which each contain 7 arrays which each contain 3 arrays which each contain 5 floats.

Length 42 snippet

interface A{static void main(String[]a){}}

A complete program. Since everything in an interface is inherently public, we can omit the word public from the main method.

Length 36 snippet

class A{class B extends A{B.B.B b;}}

A has an inner class B. This means we can declare a variable of type A.B.

But B is a subclass of A, which means it has all of the methods, fields, and inner classes of A. Thus, we can refer to the type B.B as well.

In this code, we take this a step further, and give B an instance variable of type B.B.B.

The moral: following hot questions on SO can teach you a lot of interesting, if pointless, techniques.

Length 35 snippet

l.stream().map("a"::equals).count()

If l is a list of Strings, this tells us how many of them equal "a".

Length 34 snippet

public static void main(String[]a)

Method signature of a program's main method. Just 11 more characters and we can make a complete program!

Length 33 snippet

enum D {NORTH, EAST, SOUTH, WEST}

NORTH, EAST, SOUTH, and WEST are all constants of type D.

Length 32 snippet

Files.readAllBytes("hello.txt");

Reads an entire file, returning a byte[] of the contents.

Length 31 snippet

new String(new char[]{'h','i'})

Equivalent to "hi". Useful if the " key is broken.

Length 30 snippet

new JFrame().setVisible(true);

Creates a new visible frame, which you can place other components into.

Length 29 snippet

throws ClassNotFoundException

Forces every method which call this to use a try-catch block, or else to pass the error up the stack. Checked exceptions are one of the most controversial decisions of the Java designers.

Length 28 snippet

int f(int x){return f(x-1);}

This function does not run forever; in fact, on a typical computer it takes less than a second. Thanks, Stack overflow.

Length 27 snippet

Object a=new String[]{"a"};

Creates a new array of strings.

Length 26 snippet

Object.class.newInstance()

Creates a new Object.

Length 25 snippet

((Supplier)()->-~0).get()

It's best to avoid hard-coding constants. This is an object-oriented way of getting the value 1 without using any constants other than 0.

Length 24 snippet

(Function<Long,?>)x->x+1

The successor function.

Length 23 snippet

l.removeIf(x->x%10==0);

If l is a list of integers, this removes all values divisible by 10.

Length 22 snippet

int i=(new int[7])[5];

Creates a new array of seven integers, and gets the fifth element.

Length 21 snippet

Arrays.asList(2L,"a")

Creates an ArrayList with these elements.

Length 20 snippet

System.out.print(s);

Prints s.

Length 19 snippet

import java.util.*;

Allows concise use of classes like List, Map, Scanner, Timer, and Random.

Length 18 snippet

Math.addExact(x,y)

Adds two integers x and y. If overflow occurs, the method throws an exception rather than giving an incorrect answer.

Length 17 snippet

Double.MIN_NORMAL

The smallest positive value of type double, where the leading bit of the significand is 0.

Length 16 snippet

System.in.read()

Reads a single character from the console.

Length 15 snippet

Long.reverse(x)

Reverses the bits in the binary representation of x.

Length 14 snippet

int x=050+120;

x is now 160, since anything starting with 0 is treated as octal.

Length 13 snippet

private C(){}

A private constructor prevents other classes from instantiating it. This pattern is used by the System and Math classes, among others. A private constructor can also be used to enforce the Singleton Pattern.

Length 12 snippet

Length 11 snippet

It's often necessary to throw a NullPointerException, but it's also quite wordy. This is a much simpler alternative.

Length 10 snippet

int[]a,b[]

Defines two variables: a and b. a is of type int[] and b is of type int[][].

Length 9 snippet

switch(x)

Goes to a place, depending on the value of x.

Length 8 snippet

break a;

Breaks out of the block labeled a.

Length 7 snippet

goto x;

The goto keyword is reserved in C, C++, and Java. If x is a label, then this code sends the program to the appropriate label – in C and C++. But it Java, it triggers a mysterious RuntimeException. In fact, there is no way at all to use the goto keyword in Java.

Length 6 snippet

\u003b

Ends a statement. Java is weird.

Length 5 snippet

a-=-a

Doubles a by subtracting its negation.

Length 4 snippet

a&=b

Sets the value of a to the bitwise and of a and b.

Length 3 snippet

...

Any number of arguments, consolidated into an array.

Length 2 snippet

<>

Allows the compiler to figure out what generic type you probably mean. Very un-Java-like.

Length 1 snippet

@

Indicates an annotation to allow additional information to be shown about methods and classes.

Factoid

In Java, infinite loops sometimes cause compiler errors. For example, the loop while(true); can not be terminated without exiting the method, so any code after that will trigger an "unreachable statement" error. As @Optimizer pointed out, only some infinite loops will be caught this way.

\$\begingroup\$In java, infinite loops do not cause compiler error. Its your IDE that detects them and produce an error. Java simply has a concept of Unreachable statements, so if you have something like while(true); in your code, anything put after that line will throw a compile error of Unreachable statement. The logic behind detecting such statements is very strict, so it will not recognize all infinite loops by any means\$\endgroup\$
– OptimizerJan 19 '15 at 17:48

4

\$\begingroup\$You just got down-voted, I guess this means you'll have to remove a snippet! ;) (The downvote was for "Java is weird")\$\endgroup\$
– Simon ForsbergJan 19 '15 at 20:56

Python

Now starting with the newest for your convenience!
To read through length 30 starting with the earliest first, go to revision history.

If anyone has suggestions, feel free to comment.

Length 52:

i=0
while s[i-n:]:print(' '*n+s)[i:n+i];i+=1;i**7**7

Taken from my entry in the Fake Marquee Text challenge. s and n need to be set to a string and an integer ahead of time. It doesn't actually work well in the free Python 2 interpreter I was using, so I added parentheses around (' '*n+s)[i:n+i], and you can see it run in the Python 3 interpreter here.

Length 43:

#-*-coding:rot13-*-
cevag h"Una fubg svefg"

In Python you are able to encode the source with a specific codec. This shows how the source can be written in Rot13. The general syntax is this: # -*- coding: <codec-name-goes-here> -*-.

Here it is translated:

#-*-coding:rot13-*-
print u"Han shot first"

The u specifies that the following string literal is a Unicode string. This is necessary if you want your strings to also be in Rot13, otherwise every string in the source is easily readable despite the encryption. Alternatively, you could use .encode("Rot13") after every string (don't forget to use Rot13 on this, too.) According to this article, some alternate encodings are “base64″, “uuencode”, “zlib”, or “bz2″.

Length 33:

import cmath
print cmath.sqrt(-1)

This is Python's module for complex (imaginary) numbers. This prints 1j, since Python conforms to engineering standards and uses j as the imaginary unit, though I prefer i, which is more commonly used in mathematics, and using j and k in addition to i for the quaternions, but I digress. Read the bug/change order here (it won't be changed).

Length 30:

f=lambda n:n*f(n-1)if n else 1

Now we define our own factorial function using recursion and the ternary if-else! As far as I know, this is as golfed as it gets in Python. It could also be written this way: f=lambda n:n and f(n-1)*n or 1, showcasing a couple Python's Boolean operators (and also done in 30 characters.) See the length 15 snippet for information on the lambda syntax.

This is an example of a closure. Calling cube = f(3) will make a cubic function that can then be called with print cube(24), printing 13824.

Length 19:

print"Hello World!"

Finally, enough room to print some basic output! The space is not required here, because quotes and parentheses are also delimiters. This will only work in Python 2, since Python 3 changed the print function to be called like any other function. In Python 3, use print("Hello World!"). For more information on the print function and difference between Python 2 and 3, see What's New In Python 3.0.

Length 16:

[x*3 for x in l]

Once again, assume l is a list or any other iterable object such as a string or generator. This statement is known as a list comprehension. It is much shorter than using the standard for loop structure. Here, it returns a list with all the numbers multiplied by 3. ALSO, strings can be multiplied! So any string in the list will be added (concatenated to itself) that number of times.

Length 15:

import this #:)

This is actually a length 11 snippet, but I realized I had forgotten to showcase Python's (awesome) easter egg! Importing this module prints The Zen of Python (See Factoid.) Interesting fact: the module this.py was encoded in rot13, which I will hopefully feature later.

Length 14:

lambda x:x**.5

This defines a square root function using Python's lambda syntax for a function literal. Function literals in Python can only contain expressions, not statements. This lambda could be assigned to a variable, passed to a function, or executed in-line with (lambda x:x**.5)(9), which returns 3.0. Using exponents for a square root is an alternative to importing the sqrt function in the math module.

Length 13:

1 if x else 0

This is an example of Python's ternary if operator. This was added in Python 2.5 to discourage coders from manually implementing it with Boolean operations. Here, 1 is return if x evaluates to True, otherwise 0 is returned.

Length 12:

s=input(">")

This will print > for the prompt text and allow the user to input a value. Python 2 interprets whatever value is entered, so any string needs quotes. Python 3 changed this, so that input entered is not automatically interpreted. To enter input without interpreting it in Python 2, use raw_input(). In Python 2, input() is equivalent to eval(raw_input()).

Length 11:

eval("2e3")

2e3 is scientific notation for the float 2 x 10³. The eval function interprets and evaluates any string as an expression. In this case, it has the same result as using the literal 2e3 or float("2e3"). It returns 2000.0.

Length 10:

range(013)

This function returns a list of integers from 0 to the octal value 013, which is 11 (exclusive), meaning that the list will be [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The function takes up to three parameters similar to the slice function we reviewed earlier: range(start, stop[, step]). The difference is, with only one parameter the parameter represents the stopping value.

Note that Python 3.x has no equivalent. It's range is similar, but is actually the same as Python 2's xrange, returning a generator object instead of a list.

Length 9:

a,b = b,a

Multiple assignment. This is a simple but elegant feature, allowing you to assign multiple values at the same time. In the snippet provided, it swaps a and b. What about the order of evaluation, you ask? All the expressions to the right of the assignment operator are evaluated before any of the assignments are made. This beats many languages that require an intermediate assignment to a temporary variable.

Length 8:

#comment

You know what it is... Wait, you don't? You know, those things that let you type arbitrary text to describe a line of code, making it easier to understand? No? Oh, okay...

Length 7:

l[::-1]

Again assuming l is a list, this will return the list in reverse order. The third argument indicates step size. Since all three arguments can be negative values, a negative step size means iterating in reverse order. The empty first and second arguments show that we're iterating over the entire list.

We're getting to where we can start using some more interesting constructs!

Length 6:

l[-6:]

This is called a slice operation. If l is a list, this will return a new list containing the last six elements of l as a list. -6 represents the starting index (6 from the end), and the colon means to continue until the ending index after it (which we left blank, so to the end.) If our list contained the numbers 1 through 10, this would return [5, 6, 7, 8, 9, 10].

Length 5:

1<x<5

One of Python's awesome features is allowing you to chain comparison operators. In many other languages, this would be typed as 1 < x && x < 5. It gets even better when you consider multiple comparisons: 1 < x < y < 5 is perfectly valid!

Length 4:

0256

An integer with a leading zero is a literal octal value. This is a nice trick for code obfuscation as well. This returns the decimal value 174. In Python 3.x, the octal value would be written as 0o256.

Length 3:

`3`

Surrounding an expression in backticks is the same as using repr(), which returns the string representation of an object. The function attempts to return the string in such a way that when it is passed as an argument to the eval function, it will return the original object. It is not the same as using str(), though the results are sometimes the same. For this input, '3' is returned in both cases. This is a favorite of mine for code golf!

Works in Python 2 only!

Length 2:

[]

An empty list.

Length 1:

_

The underscore character is a much-used throwaway variable name. If you are using a Python shell (interactive interpreter), however, it holds the result of the last executed statement (and would return it again.) Also, according to this thread, it is also used for translation lookup in i18n.

Factoid: Python is a language similar to Java and C. It was built with a specific design philosophy (taken from "PEP 20 – The Zen of Python":

Beautiful is better than ugly

Explicit is better than implicit

Simple is better than complex

Complex is better than complicated

Readability counts

Because of these, though semi-colons are allowed as a statement delimiter, they are usually omitted in favor of using multiple lines for readability. Also, line indentation is very important!

NodeJS again, but the principle is the same everywhere in JS. This is a very basic constructor function, which creates an object with one property (a). Setting module.exports exports the function for use by require()-ing it.

Length 46 snippet:

canvas.getContext('2d').fillRect(46,46,46,46);

This requires a <canvas id="canvas"></canvas> element. It takes advantage of the fact that elements with IDs are populated as global variables, so the element is accessible as canvas from JS. Then we fill it with a 46x46 square at x=46, y=46.

Length 45 snippet:

JSON.parse(require('fs').readFileSync('jsn'))

Back to Node. Here, we parse a JSON file named jsn from the current directory.

Length 44 snippet:

(a=document.createElement('a')).href="/url";

Building on #39. Now we create an element and assign an attribute. It still isn't in the DOM though.

Think this is not valid JavaScript? Better try it out... (use Chrome) ;)

Length 32 snippet:

document.body.innerHTML="hacked"

Halp! Hazxxors!eleven!!11!

Length 31 snippet:

a=[];for(i=0;i<31;i++)a.push(i)

No kidding, i have been waiting so long to be able to actually use a for loop! This one creates an array from 0-30.

Length 30 snippet:

new Date().getDay()==1?"S":"E"

First time using the ternary operator. I couldn't fit more than this in 30 characters, so we only know if today is Sunday, or something Else. :P

Length 29 snippet:

Object.keys(window).push('i')

Object.keys(window) will get an array of the global variables (properties of window). .push() will append an item to that array. Think this is the equivalent of window.i=undefined? Nope!

Length 28 snippet:

setTimeout("a=confirm()",28)

Waiting 28 milliseconds isn't so useful, except for creating a new thread.

Length 27 snippet:

document.querySelector('a')

It's a shame that DOM names are so long. I could only get a single link here.

Length 26 snippet:

JSON.stringify({twenty:6})

See #16. Now we get actual JSON - a string.

Length 25 snippet:

new Badge("Good Answer");

Assuming Badge() is a constructor function taking an argument... a Good Answer badge was just created!

Length 24 snippet:

do {alert(24)} while(!1)

I actually don't use do..while very much at all, but some do. If this was an ordinary while loop, it wouldn't alert anything, because it's always false. do..while will always run at least once though, so we do get to see 24.

Length 23 snippet:

window.parent==self.top

These all refer to the same object, generally known as window. If you call a function normally, there's also this. That's 5 ways of accessing the global object!

Length 22 snippet:

for(i in self)alert(i)

Alert all the global variables. It happens to be that self==window. (See the next snippet.)

Length 21 snippet:

"2"+1==21 && 2+1=="3"

Oh look, it's JS's casting rules again. This statement is true, btw.

Length 20 snippet:

Math.random()<.5?0:1

Pick a random number from 0-1, and round using the ternary operator. Though it would be easier to use Math.round...

Length 19 snippet:

[1,2,3].map(i=>i*i)

This one is new. Like, really new. It uses ES6 arrow functions to compute the squares of 1, 2, and 3. Currently, it only seems to be supported by Firefox.

Length 18 snippet:

location.href="/";

Like #15, but this time, it goes to the PPCG homepage, not SE.

Length 17 snippet:

(function(){})()

It's the snippet from 14, but better! Now it's an IIFE.

Length 16 snippet:

obj={not:'json'}

This explains one of my pet peeves. This is an object, not JSON! JSON is a data-interchange format based on JavaScript objects, but taking a more strict format.

Length 15 snippet:

open('//s.tk/')

Imagine that. Open up the SE homepage, using the http://s.tk/ redirect.

Length 14 snippet:

function f(){}

W00t! Functions! Too bad there's no room to do anything.

Length 13 snippet:

Math.random()

Generate a random number from 0 to 1. Want to define your own limits? Tough luck. (Not really, it's easy.)

Length 12 snippet:

new Date<=12

This statement has never been true in JS. JS wasn't created until '95 (see factoid), long after 1/1/1970 00:00:00.012.

Length 11 snippet:

Math.PI*121

The area of a circle with radius 11.

Length 10 snippet:

if('j')9+1

In case you haven't noticed, i like doing something with the snippet number in the code. This one returns 10, and uses j, the tenth letter of the alphabet.

Length 9 snippet:

[9].pop()

Make an array with one item. pop goes the weasel 9.

Length 8 snippet:

document

The basis for all DOM work. But we can't do anything, because it's too long. :( Go jQuery!

Length 7 snippet:

alert()

Oh boy! A function call! Finally getting to be able to do stuff!

Length 6 snippet:

var x=6

Based on #3. Much better though, because now the global is explicit. :P

Length 5 snippet:

[][5]

Even shorter than void 0 to get undefined. BTW: ''.a is even shorter; only 4 characters.

Length 4 snippet:

+"4"

This will create the number 4 out of the string "4". You can reuse these exact same 4 characters in a different order to do the opposite!

Length 3 snippet:

x=3

Oh dang, we just made an implicit global variable...

Length 2 snippet:

{}

What does this do? If you said creates an object literal, you're wrong. It's actually an empty block. Open up a console and try it! It returns undefined, not {}.

In 2018, {} in Chrome's console actually returns an empty object.

Length 1 snippet:

1

That's it. Any number is a valid JS expression.

Factoid: JavaScript was originally called LiveScript. It was changed to JavaScript to capitalize on the popularity of Java, at the time (1995). Personally, they should have kept the old name; JavaScript has been a source of confusion since. Fact is, Java and JavaScript are about as similar as "car" and "carpet".

\$\begingroup\$@Oriol Yes, well, only Firefox supports it right now, so we have to stick to the dirty way for now. At least it's better than eval(uneval(a)), right? ;)\$\endgroup\$
– ScimonsterJan 25 '15 at 12:22

R

Factoid: The R programming language began as a GNU implementation of the S programming language. It is primarily used for statistics and related applications.

Note: Though not a requirement of the competition, every snippet here can be run on its own in R.

Length 32:

`[.data.frame`(swiss,3,2,drop=F)

This looks a little mysterious... and indeed it should! There's a much better way to write this:

swiss[3, 2, drop = FALSE]

That should look a bit more familiar. Here's what happens when we run either of these pieces of code:

> `[.data.frame`(swiss,3,2,drop=F)
Agriculture
Franches-Mnt 39.7

The swiss data frame ships with R like several others we've seen so far. It contains fertility and socioeconomic indicators for 47 French-speaking provinces of Switzerland from around the year 1888. The third row is for the province Franches-Mnt, and the second column is the percent of males involved in agriculture as a profession in each province. So in 1888, 39.7% of males in the Franches-Mnt province of Switzerland worked in agriculture.

When you extract rows or columns from a data frame using the simpler notation, R is actually using [.data.frame in the background. As we saw in snippet 24, pretty much anything can be defined as a function name so long as its surrounded in back ticks, so our snippet here is legit even though the function name technically contains unmatched brackets.

The drop= argument tells R whether you want it to drop the result into a lower dimension if possible. Indeed, if we say drop=TRUE, we get this:

> `[.data.frame`(swiss,3,2,drop=T)
[1] 39.7

Where previously the result was a data frame, R now gives us a double.

Length 31:

print(fortune("hadleywickham"))

The fortune() function is from the all-knowing fortunes package, which provides a variety of wise quotes from a variety of wise folks. This snippet will provide you with the following gem from Hadley Wickham (23) by printing to the console:

That's a casual model, not a causal model - you can tell the difference by looking
for the word "excel".
-- Hadley Wickham (commenting on an Excel chart showing student's SAT score
increases with family income, without considering future covariates)
http://twitter.com/#!/hadleywickham (February 2012)

Length 30:

pie(rep(1,12),col=rainbow(12))

Who doesn't love a good pie chart? The pie() function will serve you up a freshly baked pie chart based on a vector of numbers. rep() creates a vector by repeating the first element r times where r is the second argument. The col= parameter tells pie() how to color the slices. The magical function rainbow() generates a vector of a specified length containing the hex codes for "equally spaced" colors of the rainbow.

What you have here is your basic "Amount of Each Color in This Chart" chart:

Length 29:

summary(lm(mag~depth,quakes))

There are a few things going on here, so let's take them one step at a time.

quakes is a dataset that ships with R. It contains information about 1000 seismic events of magnitude greater than 4.0 on the Richter scale near Fiji since 1964. Two of the columns in the dataset are mag, which is the magnitude of the earthquake, and depth, which is the depth of the epicenter in kilometers.

The lm() function, as mentioned in snippet 28, fits linear models. It returns an lm object, or more precisely, an object of class lm. There are two ways to specify the predictor (or independent variable) and the response (or dependent variable), and I've chosen the formula method. This takes the form response ~ predictor. Multiple predictors are specified as y ~ x1 + x2. The objects in the formula are evaluated in the context provided in the next argument.

So what lm(mag ~ depth, quakes) is doing is fitting a linear model using ordinary least squares regression where magnitude is the response and depth is the predictor. It knows what mag and depth are because we told it that they come from quakes.

summary() is a generic function used primarily for summarizing the results of fitted models. It invokes a method particular to the class of its argument. Since we passed an lm object, it's actually invoking a function called summary.lm().

Putting it all together, we get the summary of the linear model attempting to explain earthquake from earthquake depth. Specifically, this is what R spits out:

Notice how the first thing it tells you is the function call? That's because the lm() function uses match.call(), just like we did in snippet 28!

Length 28:

f<-function(x,y)match.call()

R functions often like to keep track of what you tell them. Indeed, sometimes the command you've submitted is given back to you as an attribute of the returned object. (An example is lm(), which creates linear models.) Recalling the precise instructions is accomplished using match.call() within the function. This captures, or matches, the interpreted function call.

Here we've defined a function f() that takes two arguments and then tells you what it saw.

> f(1,2)
f(x = 1, y = 2)

This is primarily useful when developing functions for general use (rather than just for you), like in package development. If you want to see an example of match.call() in the wild, look at the source code for lm() by submitting stats:::lm. One of the first things it does is capture the function call using match.call().

Length 27:

install.packages("ggplot2")

This may seem trivial, but it shows one of the reasons why R is so popular: It's very easily extensible through packages. And anyone can develop and freely share their packages!

install.packages() does precisely what its name suggests. It goes a-huntin' for packages using your default CRAN (Comprehensive R Archive Network) mirror then installs them on your system where R can find them. You can also have it install packages from local source code.

Remember snippet 23 where we used the ggplot2 package? That package does not ship with R, but in just 27 characters you can make all of your ggplot2 dreams come true by installing it.

Length 26:

filled.contour(t(volcano))

The volcano dataset ships with R. It's a matrix containing topographic information on the Maungawhau (or Mt. Eden) volcano in Auckland, New Zealand. The rows of the matrix correspond to grid lines running east to west and the columns are grid lines running south to north.

For the sake of disorientation, let's swap the directions, so columns are now east-west and rows are south-north. We can do this using a matrix transpose, accomplished via t(). And why not make a contour map while we're at it? filled.contour() does just that.

Length 25:

pmatch("s",c("n","size"))

The pmatch() function provides the magic behind all the partial matching we've seen so far. The first argument is a string which is compared against each element of the second argument, a vector. If there's a unique match, the index of the matching element is returned, otherwise you get NA.

The snippet here is a "real-world" example of the use of this function. Think back to snippet 13 where we used the sample() function. It accepts arguments n, size, replace, and prob, but only requires the first two. In snippet 13 we used s= as shorthand for size=. What's actually going on in the background is something like this snippet, where what we've provided is compared against what's expected. Since "s" matches "size" uniquely, it's totally legit to use s= as shorthand.

Length 24:

`(`=function(x)9;2*(3-1)

A perfect example of something you shouldn't do! Ever!

You can assign characters as functions so long as you surround them in back ticks when defining the function. Here we told R that ( is a function that always returns 9 regardless of the input. Like in many other languages, ; can be used for including two commands on one line. So what we've told R is to define the function (, then print 2*(3-1).

Now, just about any person would tell you that 2*(3-1) should be 4 because you do 3-1=2, then 2*2=4. But we've told R that anything inside parentheses is 9. So while 3-1=2, we now have (3-1)=9. Then we get 2*(3-1) = 2*9 = 18.

Since awful things like this are possible, every time you submit code that contains parentheses in an expression (i.e. not a function call), the R interpreter actually goes looking for any functions called ( regardless of whether you've defined ( as a function. In general, the more you write, the more work the R interpreter does.

Length 23:

qplot(Na,y=RI,data=fgl)

Finally enough votes for a (very) simple ggplot2 example. The ggplot2 package is an R implementation of the Grammar of Graphics, created by the legendary R deity Hadley Wickham. In general the syntax is very different from the base R graphics and takes some getting used to. However, qplot() is a simpler interface to some of the core features of the package and has syntax akin to plot() in base R. But unlike many of the examples I've shown you, qplot() does not support partial matching of function parameter names.

The fgl dataset comes from the MASS package. It contains measurements of properties of forensic glass fragments. Here we're using the variables Na, which is the percent sodium (Na) by weight, and RI, which is the refractive index of the glass.

Length 22:

unique(presidential$n)

The unique() function returns a vector containing the unique values from its input vector in the order in which they appear in the input. The presidential dataset ships with the ggplot2 package (27). (Thanks to Jemus42 for correcting that!) Its description:

The names of each president, the start and end date of their term, and their party of 10 US presidents from Eisenhower to Bush W.

presidential is a data frame, and data frames contain columns just as lists contain items. Columns are referenced by name using $. This particular dataset has a column called name, containing the name of the president. But wait, we only specified n! Actually, this is yet another example of partial matching (13, 16), so n is totally legit.

(Note: It has come to my attention, over a year after posting this, that the Johnson typo has been fixed. RIP humor.)

Length 21:

integrate(dexp,0,Inf)

R has a built-in function for adaptive quadrature of functions of single variable over a finite or infinite interval. In R, infinity is specified as Inf for +infinity and -Inf for -infinity. The dexp() function is the probability distribution function for the exponential distribution. Since the support of the exponential distribution is [0, +infinity) and probability distributions integrate to 1, we would expect the result to be 1. Behold, an expected result!

Looking through that you can see how it parses the function and uses the chain rule. Everything a function who took first year calculus should be able to do! The first argument to the deriv() function is an R expression (which is an actual R type) in terms of some variable, in this case x. The second argument is the name of the variable with respect to which the derivative is taken, here "x".

Want to see something really neat? Assign the above to a variable, say dx. Define a variable x as a numeric vector. Then submit eval(dx). R evaluates the derivative at x!

Length 19:

c(matrix(1,3,3),"a")

In R, c(), short for "combine" or "concatenate," creates a vector from its arguments. The elements of vectors must be of the same type and all have length 1. But instead of getting mad at you about it, R will flatten an element with structure, in this case a matrix, and cast everything to the same type.

If the arguments to c() contain only a single type, no type casting occurs, e.g. if all arguments are logicals (TRUE and FALSE), the vector will be all logicals. If it contains logicals and numbers, it will be all numbers. If it contains character and anything, it will be all character. So our snippet gives us this:

> c(matrix(1,3,3),"a")
[1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "a"

Note that the 3 by 3 matrix was flattened and the addition of "a" made everything into characters.

Length 18:

(1-1/3-1/3-1/3)==0

A lesson in machine precision. This returns FALSE.

Length 17:

example(readline)

The example() function will give you an example of how to use any built-in function. If you need to find out how to use readline(), R has a smug answer for you.

The acf() function returns the autocorrelation function for a time series. lh is a dataset that ships with R. Its description:

A regular time series giving the luteinzing hormone in blood samples at 10 mins intervals from a human female, 48 samples.

In this example, partial matching is being used twice: once with the function parameter and once with the string value passed to the parameter. The full parameter name is type and the recognized values are "correlation", "covariance", and "partial". Only enough of the string has to be provided to identify it uniquely, so we can use "part" for "partial", which gives us the partial autocorrelation function (PACF).

Length 15:

p3d(bunny,p=99)

Again we see the infamous bunny (11). The onion package gives us an even nicer way to view the most useful dataset ever, using the 3D plotting function p3d(). This calls the base graphics function persp() in the background, which takes a rotational argument phi. Using partial matching of parameter names (13), we can specify just p= in place of phi=.

Length 14:

stats:::rgamma

R is open source but you don't have to be a wizard to view the source code; you can just type the package name and the function whose code you want to view separated by three colons (:::). This gives you the code that defines the rgamma() function, which generates random deviates from the gamma distribution. Submitting this gives:

Note that it uses a function .External(). This calls functions written in other languages, typically C and Fortran, the languages which comprise much of the foundation of R. Locating that source code does take a bit of wizardry. Edit: @Vlo pointed out that mere mortals can indeed view underlying C code invoked with .Internal() and .Primitive() using the pryr package. Thanks, @Vlo!

Length 13:

sample(9,s=4)

This doesn't look like much, but it exemplifies a powerful concept in R: partial matching of function parameters. The named parameters in the sample() function are size, replace, and prob, but you only need to provide enough letters of the named parameter to identify it uniquely. Thus for sample(), you can use s= instead of size= since no other parameter names begin with the letter "s". The code here selects a random sample of size 4 from the integers 1 to 9.

Length 12:

LETTERS[-pi]

There's a built-in vector called LETTERS which contains all uppercase English letters ordered alphabetically. Unlike many other languages, you can index a vector using a floating point number. Nothing too exciting happens; R just takes the integer portion. Using - preceding the index of a vector removes the element with that index from the vector. pi is a built-in constant containing--you guessed it--the irrational number π. So this removes element 3 from the vector and returns "A" through "Z" omitting "C".

Length 11:

plot(bunny)

In the onion package, there's a dataset called bunny. Plotting it gives you what may be the most useful graphic of all time:

Length 10:

????sample

Say you're REALLY confused about the sample() function and you desperately need help. Rather than the usual ?sample to pull up the R manual page, you pound out four question marks. R hears your plight and attempts to help...

Contacting Delphi...the oracle is unavailable.
We apologize for any inconvenience.

Alas.

Length 9:

isTRUE(1)

At first this looks to defy the convention in the rest of the R base package to separate is and the following word in the function name with a .. However, that only applies to a logical test of whether the argument is of a certain type, as below (8). In this case, we're testing whether it is TRUE, which is not a type. This uses a strict definition of TRUE, i.e. 1 is not "true" in the usual sense. isTRUE(1) returns FALSE.

Length 8:

is.na(8)

Unlike most other programming languages, . is a valid character in function and variable names. It does not denote any sort of method or heirarchy; it's just part of the name. The is.na() function checks whether its argument evaluates to NA (missing) and returns TRUE or FALSE.

Length 7:

stop(7)

This issues an error with the input as the error message. If called inside of a function, the function execution will stop. But calling it outside of a function won't stop the script. In this case, the output is Error: 7.

Length 6:

x < -1

While this may seem trivial, it displays a major criticism of the assignment operator <-: namely, the meaning changes depending on the placement of spaces. As mentioned, x <- 1 assigns 1 to x. Separating < and - with a single space as above changes it to a logical test of whether x is less than -1. For that reason, many prefer = for assignment.

Length 5:

x<<-1

Similar to <- except <<- always assigns the variable to global scope regardless of the current scope.

Length 4:

x<-1

R uses <- to assign variables in the current scope. This snippet assigns the value 1 to x.

Length 3:

!0i

The ! operator is R for "not," and 0i is the complex number 0+0i, AKA 0 in the complex plane. Submitting this statement returns TRUE since 0 is false.

Length 2:

NA

This returns the special R value NA, which stands for "not available," denoting a missing value.

Length 1:

T

This returns TRUE. In R, T and F are synonyms for the boolean values TRUE and FALSE, respectively.

\$\begingroup\$How do I upvote more for more entries???? "Locating that source code does take a bit of wizardry" is trivial for .Internal and .Primitive -> pryr::show_c_source(.Primitive("sum"))\$\endgroup\$
– VloJan 23 '15 at 20:31

\$\begingroup\$@Vlo: I hadn't heard of the pryr package. Very cool! Thanks for pointing that out. I'm glad you like the entries so far, thanks for the support. :)\$\endgroup\$
– Alex A.Jan 23 '15 at 21:05

Factoid: Brainfuck (Also known as brainf*ck) was a experimental esoteric language for creating the smallest turing-complete language interpreter ever, created by Urban Müller, and is currently the most famous language of its kind. It has only eight commands, is easy to learn, but hard to use.

Brainf*ck has a tape base memory with 30000 cells and a a movable pointer, and can be visualized like this:

0 0 0 0 0 0
^

With the ^ character representing the pointer, and the 0's representing the values for each cell.

Brainfuck has eight instructions:

Instruction C Equivalent Description
+ mem[ptr]++; Add one to the value under the cell
- mem[ptr]--; Subtract one from the value under the cell
> ptr++; Go on cell to the right
< ptr--; Go on cell to the left
, mem[ptr] = getchar(); Read a ASCII character from input and put the result in the value under the cell
. putchar(mem[ptr]); Write a ASCII character to the output using the value under the cell
[ while (mem[ptr]) { Start a while loop: Continue to matching ']' when value under the cell is 0
] } End a while loop: Go back to matching '[' when value under the cell is NOT 0

C++

With its preprocessor, templates, lambdas, type traits and countless other complex features that no one can ever hope to understand in its entirety, C++ is rediscovered by each new generation of its standard. By exploiting its numerous ways to do things at compile time, one can write zero overhead abstractions like a library that allows physical units being attached to numeric datatypes in order to check their soundness at compile time (e.g. you can not assign the outcome of kg*m to N)

Length 1

#

Usually introducing a preprocessor statement, # can stand on a line on its own. It essentially means nothing and seems to be so unknown that most syntax highlighters I see don't know it.

Length 2

%:

Of course not everyone has a # key, so C++ is (well, it really inherited it from ancient C) generous to allow you to write it with this alternative token (aka digraph)

Length 3

??=

This is a historical course on C++. These days not necessarily valid anymore, though implementations can support them, are trigraphs. This sequence is translated into # on those systems that support it, but to not interfere with raw string literals, it is not allowed within those. Implementations may chose to drop support alltogether.

Length 4

auto

Is one of the newer (since C++11) inventions to make working with generic code easy. It is for deducing the type of an expression, and since C++14 it can even be used for deducing lambda parameters and the return type of functions.

Length 5

catch

Is a keyword that is also known from many other languages, present in C++, but the good idiomatic C++ programmer does almost never use it. With its constructors and destructors idiomatic C++ uses a principle widely called RAII (Resource Acquisition is Initialization) or how I like to sometimes call it more appropriately: SBRM (Scope Bound Resource Management). Due to classes like smart pointers, one can tie the lifetime of dynamically allocated resources (that is not only memory!) to other objects. When those go out of scope (e.g. by a thrown exception), these objects automatically clean up resources. This allows for exception safe and easy to use code that doesn't need to use catch.

Length 6

[](){}

[]{}()

As stefan mentioned in the comments, you can use []{} as the shortest lambda object, thus this is the shortest form to call a lambda. The following text is for the old version:

is probably the shortest form of a lambda. Lambdas in C++ are objects (of implementation defined type) that are able to capture part of the scope they are created in (the [] syntax controls this), and are callable (the () syntax controls this). Their code (The {} part) has access to these variables as if they were within their scope. With their optional return type deduction and auto parameter deduction introduced in C++14, they are the tool to use for all the standard library algorithms that expect a callable (e.g. the third std::sort parameter).

Length 7

virtual

Is the keyword to start using runtime polymorphism in C++, one of the basic blocks of object oriented programming. This follows the "don't pay for what you don't use" principle, wheras in other languages all functions are virtual by default. Being a multi paradigm language, it might be a surprise for people thinking "C++ is object oriented" to see programs or libraries that make almost no use of this keyword, e.g. because they follow the generic programming principle.

Length 8

override

Working together with the virtual keyword, override is one of the later additions to C++ to make the compiler do more work for you. By using it, you express the intention of overriding a virtual function in the base class, and the compiler will error out if you did a mistake and that class doesn't have the specified function. In general it is considered good style if your code expresses the intention, rather than fiddle with bits.

Length 9

constexpr

Being also a later addition to C++, constexpr allows the programmer to express for functions or variables, that they are known at compile time and should be computable at compile time. This allows these functions to be used in contexts that need compile time expressions (e.g. as template parameters or array sizes). Many standard library functions (if possible) are already constexpr so they can be used here.

Length 10

for(i:c){}

Is a complete loop over a container, or container like construct that supports std::begin and std::end to get iterators (that includes C style arrays). It is basically equivalent to for(auto __i = std::begin(c); __i != std::end(c); ++__i){ auto& i = *__i; }. This allows for easy looping in generic code.

Length 11

void f()&&;

Is a new way to declare member functions and the properties on the object they can be called on. In previous versions of C++ we only had the ability to chose void f() const; to tell the compiler to be able to call the function on const objects (thus without the const you can not call them on non-const objects). The same way we now have the && syntax for r-value references being used to be able to call those functions on rvalues.

Length 12

int main(){}

This is probably the shortest complete program that you can compile link and run. It will do nothing and return 0. This return is one of the many special cases you can encounter in C++. Normally returning nothing is undefined behaviour, but for the entry point function main, returning nothing means returning 0.

Length 13

auto f()->int

is a rather new way to declare the return type of a function. Normally you would not do this if you already know the type, but there are plenty of situations in generic programming where the type depends on template parameters and the variables you use. Doing it this way allows for a somewhat easier access to these parameters as in template<class T> auto f( const T& t ) -> decltype(t.foo()) instead of template<class T> decltype(std::declval<T>().foo()) g( const T& t ) { return t.foo(); }

\$\begingroup\$I would suggest using ; as an alternate 1-char snippet, because it's not a preprocessor macro and the fact that you can have a 1-character statement in C++ at all seems baffling.\$\endgroup\$
– Joe Z.Jan 24 '15 at 5:57

1

\$\begingroup\$[](){} isn't the shortest form of a lambda: As the list of parameters is empty, it may be omitted. Hence []{} is the shortest lambda. Trivially, []{}() is the shortest execution of a lambda ;-) ideone.com/k8fAvs\$\endgroup\$
– stefanJan 28 '15 at 12:01

\$\begingroup\$@stefan: indeed, I always forget it since it doesn't look function like then ;) I added it to the answer.\$\endgroup\$
– PlasmaHHJan 28 '15 at 13:11

\$\begingroup\$@PlasmaHH I absolutely hate it because indeed it doesn't look like a function.. ;-)\$\endgroup\$
– stefanJan 28 '15 at 14:20

Python re (tested on 2.7.8 and 3.2.5, may be different on 3.3+): In default mode, dot-all matches any UTF-16 code unit (0000 to FFFF inclusive), except for \n. re.DOTALL lifts the exception and makes . matches any UTF-16 code unit. In these versions, re operates on UTF-16 code units, so . only manages to match one code unit of characters in astral plane.

PCRE: Depending on build option, dot-all can exclude \r, \n or \r\n, or all 3 CR LF sequences, or any Unicode newline sequence in default mode. In default mode, the engine operates on code unit (can be 8, 16, or 32-bit code unit), so dot-all matches any code unit, except for the newline sequences. In UTF mode, the engine operates on code point, so dot-all matches any code point except for newline sequences. The dot-all mode is called PCRE_DOTALL.

PHP (tested on ideone): PCRE, compiled as UTF-8 library and \n is the only newline sequence by default. Dot-all mode is accessible via s flag.

Postgres: In default mode, dot-all matches any code point without exception.

\$\begingroup\$You can read the Zalgo'ed text, but don't take them too seriously in both directions. It is plain wrong to follow the way of Zalgo blindly, but the Zalgo text is not wrong all the time.\$\endgroup\$
– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳Jan 20 '15 at 17:08

12

\$\begingroup\$@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, aren't you going to use all those votes to show us how to parse HTML?\$\endgroup\$
– mbomb007Jan 23 '15 at 15:49

A dense one... First, verbs (as J calls functions) are organized by theme. All ^ verbs are tied to exponentiation. ^ for exponentiation (and exp when used monadically, ^. for logarithms. ^: is a special one, the Power conjunction (a higher order function), which applies a function a number of times. When right the argument is infinity (_) it executes its left argument (in the example ^.) on its own output till it converges. In effect, ^.^:_ is a verb solving x = ln(x) when applied to any argument but 1, yielding 0.318132j1.33724.

A fork is composed of 3 verbs without any reference to arguments. This allows what in J is called tacit (point-free) programming. A fork f g h, in the monadic case (as in this example) is equivalent to (f y) g (h y).
As forks, multidimensional arrays are an intrinsic part of J. "Indices" returns the indices of ones in a vector, but does not extend to higher dimensions as such.
This example uses Shape, Antibase and I.@:, as the 3 tines of the fork implementing I. for higher dimensional arrays, for instance:

Boxed arrays are a data type in J, allowing to combine heterogeneous content (both type and size) into one value. Monadic <boxes it's argument.
Rank is a central concept in J, and allows to automatically extend verbs towards arrays of higher dimensions. Both nouns and verbs have a rank.

Noun rank is the number of dimensions of any noun, which the verb $@$ can tell you. For example i. 2 3 4 is an array of rank 3.

Verb rank is the rank onto which a verb will apply itself. Every verb has an intrinsic rank which can be queried with the Basic conjunction. v b. 0 returns 3 numbers for the monadic, dyadic left and dyadic right rank of the verb v.

A verb works on noun cells of rank equal to the verb rank, and replaces results in a noun rank-verb rank frame.
A verb's rank can be limited using the Rank conjunction, as is done here, boxing rank 1 cells (rows) instead of working on rank _, ie. boxing the entire array. More info on rank can be found here.

This snippet is a verb calculating the shortest path over weighted digraph.
It introduces minimum (<./) and the Dot conjunction.
The dot conjunction is a generalization of the matrix product,
which can be written as +/ . * . Generally, u . v is equivalent to u@(v"(1+lv,_)) where lv is the left rank of the verb v. Or in words "u is applied to the result of v on lists of “left argument cells” and the right argument in toto". (See above for ranks)

As such the inner verb <./ .+~ replaces item y(i,j) with the minimum of y(i,k)+y(k,j) for all k.

This snippet introduces special code: Some J code is supported by code specifically written for a certain use case, recognized at parse time, and optimized;
either for higher accuracy (as is the case here) or higher performance (see Special combinations)

This phrase gives 99 digits of pi (though shifted 99 decimal places). Special code depends on exact phrasing, what would normally be equivalent is not as precise as the snippet code: <.o.10x^99looses the extended precision.

From time to time, you end up in situations where due to selections made in data,
there are singleton dimensions running in the way.
This handy utility, called squeeze in Matlab, squeezes out all singleton dimensions.
The left tine of the fork ($-.1:) yields all dimensions without the ones, while the middle one ($,)
reshapes the raveled array to the dimensions retained. The right tine ] serves just to make this a fork, and references the right argument.

Newton's Method finds an approximation of a root of a differentiable function.
This explicit adverb is to be applied to the function of which the root is sought, and represents one step of the iterative procedure.
u is the argument referencing the function, being replaced the moment the adverb is applied. d. is a conjunction deriving functions symbolically, and might here be replaced by D. which does the same numerically (but differs when applied to higher rank functions). The result is a hook subtracting the fork ( u divided by its derivative) from the argument.

Another take on Fibonacci series. This time from another angle; starting from Pascale's triangle '!/~i.9' .

/ when used dyadically means Table, applying the verb it's bound to between each cell of it's arguments, yielding a table of the operation between arguments x and y.
In this case ! used dyadically, as Combination (or Out of). ~ makes the verb Reflexive, ie. use it's right argument as the left one too.

The adverb /. is an odd one, it applies it's verb along the anti-diagonals of an array (ie. try </.!/~i.5 here )

So this snippet takes the sums on the 9 first anti-diagonals on the Pascal's triangle, which happens to be another occurrence Fibonacci series.

Ok, I added a space just to get to 16 :). This snippet demonstrates a fork using Key:
listing all items in the argument and their frequencies.

x u/. y applies u to y in chunks where x is unique, or in J : (=x) u@# y, where = is Self-Classify,
which generates a boolean array containing 1's in positions where they appear in the nub~.
Here it's applied reflexively, hence executing Tally
on each unique item in y, counting the number of appearances.

As most verbs in J keep the nub order (order of appearance of new unique items, opposed to for instance unique in Matlab, which sorts its argument) this can be used for Stiching the items
to their frequencies as is done here. ;/@~. is used to make a boxed list of all items.

This snippet is a verb that takes an anagram index to the left (between 0 and !#y) and right argument y an array to permute.
Afterwards, it computes the LCM*./ of the cycle lengths #&>, ie. the period after which you get the original array back:

This little verb comes from the "stats/base" add-on, and is called histogram.
It does exactly that, given a list of bin starts, sums all occurrences of data between in the interval ]bn-1,bn] where bn is the start of bin number n.

This is a big stretch on whether or not we can consider this a real programming language or not, but we will try anyway. And, as these two "languages" are practically the same, I will combine them, sometimes post snippets in "Minecraft" language (redstone, etc) and sometimes in RPL. Also, since many snippets will be in Minecraft, I will post links to the pictures rather than the pictures themselves to save space. Additionally, all snippets will be of programming concepts in Minecraft, not general redstone (i.e. no redstone doors will appear). Characters will be counted in bytes (in RPL) or as according to this (in Minecraft).

Factoid:

RPL is a programming language by Tossha the Inventor that converts code into Minecraft redstone and command blocks. It can do input and output, loops, integer manipulation, trig functions, roots, and more.

Length 1:

A button (1 byte) is the simplest form of input in Minecraft. It also can start or stop a "program". Similarly, a lever (also 1 byte) is another form of input, and can also be used to both start and stop the program as it has an "on" and "off" state. Something to remember is that Minecraft is literally a 3D programming language, so where the button/lever is place in the program can make a huge difference.

Length 2:

A button attached to a redstone lamp is pretty much your very basic cat program. It takes the input (with a button or lever, either 0 or 1 (off or on)) and outputs it in the form as light from the lamp as either 0 or 1 (off or on).

Length 3:

As seen below, this one of the shortest source-code modifying programs (as you can modify the source at runtime with Minecraft!). Now, this specific one really has no use, but the concept can be combined with others to create some awesome programs (as to come with more upvotes). When run, this program removes its source of input, and makes itself unable to be run again.

Length 4

This "snippet" actually shows two concepts: delay, and the NOT gate. Delay is made using certain redstone elements that have a redstone-tick delay. A redstone-tick is equal to one-tenth of a second. Different redstone components have different delays: a torch has a 1rt delay (1 redstone-tick), a comparator has a 1rt delay, a repeater can have a 1, 2, 3, or 4rt delay, depending on how it is set up. In this example, the redstone repeater is set to a 4rt delay.

Next is the NOT gate. The NOT gate takes an input an inverts it. So in this set up, the output will be on if the input is off, and the output will be off if the input is on.

Length 5

The OR gate is very easy to accomplish in Minecraft. Two inputs are connected to the same output. That is it. No funny trickery or anything, it's pretty simple.

Length 6

Here is a tip for compacting your "code". If you know the signal strength of two inputs are small enough to not interfere with the corresponding outputs, you can wire the redstone right nect to each other. In the example below, there is a simple hopper timer, which transfers items back and forth in about 0.5s in each hopper, conncected to comparators that output a signal strength of 1. This means that the two ouputs will not interfere with each other. In the example, the lamps are there for demonstration purposes only and don't count towards the total block count.

TI-BASIC

[The language varies based on which calculator it is used on, but these will use the TI-84 unless otherwise noted.]

Length 31 snippet

Menu("","1",A,"2",B
Lbl A
Lbl B

This demonstrates the use of menus. The one above is quite useless, as it does nothing, but they can be used to navigate the different part of a program. The first argument is the menu title, followed by pairs of options (the string displayed followed by a 1- or 2-letter label). Here is a more intuitive example:

Lbl can also be used for branching with Goto. Menus have some limitations that make them annoying to use, however: There can only be seven menu items, and each title can be at most fourteen characters, so the whole thing fits on one screen.

Length 29 snippet

Real
√(-16
a+bi
Ans
re^θi
Ans

Real (on by default) places the calculator in real number mode, so calculations involving complex numbers throw a NONREAL ANS error. When put in a+bi mode, the calculator displays answers as complex numbers if applicable, so the second example returns 4i. re^θi mode uses polar instead of rectangular coordinates, so it outputs 4e^(1.570796327i).

Length 23 snippet

If A≥9
Then
1→X
7→Y
End

This is just a simple conditional, although there can be an Else statement. Then and End are not required if it is just one statement.

Length 21 snippet

(-B+√(B²-4AC))/(2A)→X

Everyone's favorite, the quadratic formula. Stores the first solution to a quadratic equation as X, assuming a, b, and c are stored in their respective variables, as in ax2 + bx + c.

Length 20 snippet

Shade(|X/2|-3,5-X²,0

This shades the intersection of the two functions, with several optional parameters: minimum and maximum values of x and direction of and distance between the shading lines.

Length 18 snippet

LinReg(ax+b) L1,L2

Here we calculate the linear regression equation, or the linear equation that best matches a group of points, with the x-values stored as a list in L1 and the y-values in L2. There are many other regression options available, including quadratic, cubic, and exponential.

Length 17 snippet

dbd(1.2711,1.2115

This calculates the number of days between two dates, in this case January 27, 2011, the day this site started, and January 21, 2015, the day this was written. (That's 1455 days for the lazy.) The way to encode dates is a little strange: either DDMM.YY or MM.DDYY, leading zeroes optional.

Length 16 snippet

For(A,0,5
Disp A

This shows two parts of the programming side of the language. The first is your typical for loop, similar to for(var A=0;a<5;a++) in other languages. (You should also use the End command to break out of the loop.) The second is self-explanatory: it displays A, in this case 5 times because of the loop.

Length 15 snippet

Y1=|X³-4|
Y2=3X

Here are two examples of a well-known feature of graphing calculators: graphing equations. You can have 10 different equations graphed on the same plane, and there are many useful commands to find intersections, maxima, values of x, etc. Those equations look like this when graphed on a standard window:

Length 14 snippet

[[1,2][34,5]]T

The brackets are used to make matrices, and the T transposes the matrix:

[[1 34]
[2 5]]

Length 13 snippet

dayOfWk(9,1,6

This finds the day of the week of January 6, 9 AD. The output is a number where 1 is Sunday, 2 is Monday, and so on. This particular date was a Tuesday, so the output is 3.

Length 12 snippet

Circle(1,3,5

The first of the basic drawing tools, this draws a circle on the graph with a center at (1,3) and a radius of 5.

Length 11 snippet

randInt(0,8

This generates a (pseudo-)random integer between 0 and 8 inclusive. There is an optional third argument that tells how many integers to generate. There are several other random functions, including ones for normal and binomial distributions, one for a random matrix, and one for a randomly ordered list with no repetitions. randInt can be seeded by storing a number as rand: 2→rand.

Length 10 snippet

4>5 or 2≠7

Here we have TI-BASIC's (in)equality and logic operators. The inequality statements evaluate first to 0 or 1, and or returns true if either side is true, so this displays 1.

Length 9 snippet

.656▶F◀▶D

This can convert from decimal to fraction and vice versa, which is very useful. There are also dedicated ▶Frac and ▶Dec functions that only go one way. Prints 82/125 in this case.

Length 8 snippet

Length 7 snippet

getDate

Pretty self-explanatory, just prints the current system date as a list, in this case {2015 1 19}.

Length 6 snippet

√({4,9

Arrays (or lists) are surrounded by braces and separated by commas. This is similar to the map function of many languages, where it iterates through each element of the list and applies the operation outside the braces to it, in this case square root, so the result is {2 3}. Note that closing parentheses are optional, so they will be omitted from now on.

Length 5 snippet

4iii6

We've got a couple of cool things going on here. First, the real parts, 4 and 6 are multiplied, and then the imaginary parts are multiplied: i^3, or -i. These multiplied give -24i. This showcases funky-looking juxtaposition multiplication and TI-BASIC's handling of imaginary numbers.

Length 4 snippet

8°5′

This is 8 degrees, 5 arcminutes, which is converted to degrees as 8.0333...

Length 3 snippet

8→T

This shows how numbers can be stored as variables, which is somewhat unusual because the number goes first, followed by the store arrow, then the variable name. As mentioned in the factoid, θ (theta) can also be used as a variable, and variables can only be one uppercase letter.

Length 2 snippet

4M

Similarly to Mathematica, you can multiply with juxtaposition, no * necessary. All variables are initialized to 0 by default, so this will output 0 unless you have stored something else to that variable (see snippet 3).

Length 1 snippet

e

This is the constant for Euler's number, which displays as 2.718281828.

\$\begingroup\$By the way, the lower case n (not n) can also be used as a variable.\$\endgroup\$
– YpnypnJan 21 '15 at 15:28

\$\begingroup\$Interesting. I've never used that variable.\$\endgroup\$
– NinjaBearMonkeyJan 21 '15 at 16:40

3

\$\begingroup\$One can argue about str0 being 1 character or being 4. All instructions in TI-BASIC are 1 character long.\$\endgroup\$
– Ismael MiguelJan 23 '15 at 18:51

\$\begingroup\$@IsmaelMiguel I thought about that, but they are 1 or 2 bytes, and I decided to count characters normally.\$\endgroup\$
– NinjaBearMonkeyJan 23 '15 at 19:27

1

\$\begingroup\$I respect your decision. It helps a lot in this case. I really enjoyed programming on my oldie TI-83. (I've even designed a paint program in it!)\$\endgroup\$
– Ismael MiguelJan 23 '15 at 19:31

GNU Sed

Factoid

Length 0 Snippet

I don't think a length 0 snippet is strictly required, but since it actually does something in sed, here it is:

Sed is the "Stream EDitor", i.e. it reads the stream (line-by-line) from STDIN, edits, then outputs to STDOUT. The zero-length sed program simply copies STDIN to STDOUT. Thus the cat utility may be emulated by sed. The following are equivalent:

cat a.txt b.txt > c.txt

and

sed '' a.txt b.txt > c.txt

Length 1 Snippet

=

This sed program prints the line number of each line to STDOUT. This is approximately equivalent to:

nl

or

cat -n

although the sed version puts the line number on its own line.

Length 2 Snippet

5q

Copies STDIN to STOUT and quits after line 5. This is equivalent to:

head -n5

You might be starting to see a bit of a pattern here - sed can be used to emulate many of the standard core-utils tools.

Length 3 Snippet

iHi

inserts "Hi\n" before every line. Meh.

Length 4 Snippet

/a/d

A lot of sed's power is in its regex capability. This program causes all lines matching the regex a to be deleted from the stream. All other lines will still be output to STDOUT. This is equivalent to:

grep -v "a"

Length 5 Snippet

:l;bl

This is an infinite loop. We all love CPU-hogging infinite loops. Defines a label l, then branches (jumps) to it. Ad infinitum.

Length 7 Snippet

s/a/A/g

By default, sed applies s commands such that it will match just the first occurrence on each line. If you need it to match (and substitute) every occurrence on a line, then the g flag at the end of the s command will do this.

Length 8 Snippet

y/01/10/

The little used y command is similar to the tr shell utility (though not quite as flexible). This program will switch all 0s with 1s and vice versa.

Length 9 Snippet

1!G;$p;h

This snippet is actually 8 bytes, but requires the -n parameter to sed to suppress default output, so as per standard code-golf rules, I'm counting this as 9. This program reverses the lines in the stream. So:

sed -n '1!G;$p;h'

is exactly equivalent to:

tac

Length 10 Snippet

s/[ <TAB>]+$//

This is a revisit of the (incorrect) length 6 snippet. This strips trailing whitespace (spaces and TABs) from lines.

\$\begingroup\$Nice, but please note many of these use GNU extensions and are not standard—specifically length 3 (standard would be i\<newline>Hi<newline>), length 5 (standard would be sed -e :l -e bl or :l<newline>bl<newline), and length 10 (which needs the + turned to a * to work at all). Note that the length 9 snippet -n '1!G;$p;h'is standard, whereas tac is not. :)\$\endgroup\$
– WildcardNov 10 '16 at 7:59

Python

(mbomb007's post already has a plethora of Python snippets, but I thought I'd chip in with some quirkier facts)

Factoid

Python is a dynamically typed language with an emphasis on readability.

Length 1 snippet

1

In Python 3, the above is equivalent to True in the sense that 1 == True (and also 0 == False). Note that this doesn't necessary hold true in Python 2, where you can redefine the value of True.

Length 2 snippet

<>

<> is an obsolete comparison operator equivalent to !=. It still works in Python 2 (although its use is discouraged), and was removed altogether from Python 3.

Length 3 snippet

...

Python has a number of features which no builtin uses, but is there solely for the sake of third-party libraries. This Ellipsis object is one of them, and it is typically used for slicing. For example, if we have the following 3D numpy array:

array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

then a[..., 0] (equivalent to a[:,:,0]) gives all the first elements:

array([[1, 4], [7, 10]])

In Python 3 the ... literal can be used outside of the slicing syntax, which amusingly allows you to use it as a "to-do" marker in place of pass or NotImplemented:

def f(x):
... # TODO

Length 4 snippet

(1,)

A one-element tuple in Python.

Python has lists (e.g. [1, 2, 3, 4]) which are mutable, and tuples (e.g. (1, 2, 3, 4)) which are immutable. One common use for tuples is as dictionary keys, since lists aren't hashable.

A common beginner mistake is to leave out the comma above, i.e. (1), which is just the number 1 surrounded by parentheses. The one-element tuple is the only time you need a comma before the closing parens — it raises a SyntaxError if you try to put one in the empty tuple (), and is optional for tuples of length at least 2.

Length 5 snippet

0or x

There's a few things going on in this snippet, so let's take a look!

or is like || in many languages. In Python, A or B short-circuits, returning A (without evaluating B) if A is truthy, otherwise it returns B. For example, 1 or x always returns 1, as 1 is always truthy, and even works if x is not defined. On the other hand, 0 or x either returns x if x is defined, or throws a NameError if it isn't.

When golfing, we can usually drop the whitespace between a number and an or, such as 1 or x becoming 1or x. This is possible because 1or starts with a digit, making it an illegal Python identifier.

However there is one exception — 0or, which mysteriously throws a SyntaxError. Why? Because octal literals in Python start with 0o (e.g. 0o20 == 16), and the parser chokes when it reaches the r!

Note: In Python 2, octal literals may also start with a leading zero, e.g. 020.

Length 6 snippet

*x,y=L

This snippet demonstrates a special type of assignment in Python, where L is a list, tuple or any other sort of iterable.

In Python, you can "unpack" tuples and lists like so:

a,b = [1,2]

This assigns 1 to a and 2 to b. This syntax is also used for multiple assignment, such as

a,b = b,a+b

which is useful when writing a program that computes the Fibonacci series.

If the lengths on both sides don't match, then a ValueError is thrown. However, Python 3 introduced a new syntax, extended iterable unpacking (or more colloquially, "starred assignment") which allows you to do things like this:

*x,y = [1, 2, 3, 4, 5]

This assigns y to the last element, 5, and x to the rest of the list, i.e. [1, 2, 3, 4]. You can even do something like this:

a,b,*c,d,e = [1, 2, 3, 4, 5, 6, 7]

which assigns 1 to a, 2 to b, [3, 4, 5] to c, 6 to d and 7 to e.

Length 7 snippet

zip(*x)

zip is a function which takes a bunch of lists and, well, zips them up:

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]

Note: In Python 3 a zip object is returned instead, so if you want a list like above you'll need to wrap the call in list()

It's quite a convenient function if you have two or more related lists, and you want to link up their respective entries.

Now say you want to unzip the list — how would you do so? We can try to use zip again, but unfortunately this gives:

>>> zip([(1, 4), (2, 5), (3, 6)])
[((1, 4),), ((2, 5),), ((3, 6),)]

The problem is that everything is in the one list, but zip takes the individual lists as separate function arguments. To fix this we introduce the * splat operator, which takes a list/tuple/etc. and unpacks them as function arguments:

f(*[1,2]) ==> f(1, 2)

And the result is:

>>> zip(*[(1, 4), (2, 5), (3, 6)])
[(1, 2, 3), (4, 5, 6)]

Length 8 snippet

x='a''b'

The first time I saw this, I was a little taken back — what does it mean to have two strings next to each other? The answer was simple:

>>> x
'ab'

Python merely concatenates the two strings! This is extremely useful for readability, since it allows you to break up long strings like so (note the surrounding parentheses):

x = ('This is a very long sentence, which would not look very nice '
'if you tried to fit it all on a single line.')

Length 9 snippet

0!=2 is 2

You may already know that Python allows chaining of comparison operators, so 5 < x <= 7 is only true if 5 < x and x <= 7. If you didn't know that... then surprise!

Anyhow, lesser known is the fact that, since is/is not/in/not in are also comparison operators, they can be chained too. In other words, the above code is equivalent to (0 != 2) and (2 is 2), which is True.

Note: There are a few subtleties with the 2 is 2 half though, since is checks whether two things are the same object, not whether two things are the same value. Python caches small integers so 1+1 is 2 is True, but 999+1 is 1000 is False!

Length 10 snippet

x=[];x+=x,

What happens when you add a list to itself? If we try printing x, we get:

[[...]]

Fortunately, Python's print is intelligent enough to not explode trying to print recursive lists. We can then do a bunch of fun things, like:

>>> x[0][0][0][0][0]
[[...]]
>>> x[0] == x
True

This feature also works with dictionaries, and is one way of creating data structures with cycles, e.g. a graph.

Length 11 snippet

help(slice)

The help function is very useful for debugging in Python. When called with no arguments in REPL, help() starts a help session, in which you can look up documentation for functions/data types/etc. When called with a specific argument, help will give information on the related item.

For example, help(slice) gives the following information (truncated since it's quite long):

Another useful function for debugging is dir(), which returns all names in the current scope when called without an argument, and returns all attributes of a given object when called with an argument.

Length 12 snippet

round(5.0/2)

What does this evaluate to? The answer depends on your Python version!

In Python 2, division between two integers results in integer division (i.e. 5/2 == 2) whereas in Python 3 we get float division (i.e. 5/2 == 2.5). However, this is division between a float and an integer, which should always result in a float. Why would we get different results then?

If we take a look at the documentation for round for both Python versions, we'll find the answer:

In Python 3, round tiebreaks by rounding towards the closest even integer.

In other words, 5.0/2 = 2.5 rounds to 3 in Python 2, but rounds to 2 in Python 3. Rounding towards the closest even integer might sound weird, but it's actually called banker's rounding, and tries to treat positive and negative values similarly to reduce bias.

Length 13 snippet

class C:__x=1

Being object-oriented, Python has classes. The above is a class C which has a single attribute __x set to 1.

We can access class attributes using dot notation. For example, if we have the class

class MyClass(): my_attr = 42

then printing MyClass.my_attr would result in 42, as expected.

However, if we do the same and try to access C.__x as defined above, we get:

AttributeError: type object 'C' has no attribute '__x'

What's going on? C clearly has an __x attribute!

The reason is that attributes starting with __ emulate "private" variables, something which Python does not have. Python mangles the name of any attribute starting with __, appending the class name so that name reuse conflicts are avoided. In the above example, if we were really determined to access that 1, we would instead have to do

>>> C._C__x
1

Length 14 snippet

NotImplemented

Not only does Python have classes, it also has operator overloading. For example, you can have a class

class Tiny():
def __lt__(self, other):
return True

where __lt__ is the less-than operator. Now if we make an instance of Tiny, we can do this

>>> t = Tiny()
>>> t < 1
True
>>> t < "abc"
True

since we've defined __lt__ to always return True. Note that we can also do

Wait, how does that work? We haven't specified a behaviour for greater-than with Tiny, so it's not surprising that the last case breaks. But then how does an int (42) know that it's greater than our Tiny object?

Python has a builtin constant NotImplemented, which can be returned by a comparison special method. Let's try it out:

As we can see, what happened for u > t is that Python tried to call the greater-than method for Unknown first, found that it was not implemented, and tried the less-than method for the other class (Tiny) instead!

Length 15 snippet

x=[],;x[0]+=[1]

This is a bit of a fun one. First we assign x to be [], which is an empty list inside a tuple, i.e. ([],). Then we do x[0]+=[1] which tries to extend the empty list inside by the second list [1].

Now, remember that lists are mutable and tuples are immutable – what happens when you try to change a mutable object inside an immutable object?

Oh so it gives an error, I guess that's to be expected. But what if we try to print x?

>>> x
([1],)

Huh? The list changed!

If you're curious about what's happening here, be sure to check out this blog post.

Length 16 snippet

@lru_cache(None)

Just add cache! This is a simple example of a decorator available in Python 3.

Suppose we have the following naïve Fibonacci implementation:

def f(n):
if n < 2: return 1
return f(n-1) + f(n-2)

As most introduction to programming courses may tell you, this is a very bad way of implementing Fibonacci, leading to exponential runtime since we're effectively just adding a lot of 1s at the base case. f(10)? Runs in a split second. f(32)? Take a while, but it gets there. f(100)? Nope.

But if we cache the results, things should get a lot faster. We could always use a dictionary for the cache, but let's try something else instead:

As we can see, all I've done is import lru_cache from the functools module and added @lru_cache(None) before my function. @ denotes a decorator which wraps around a function, in this case for memoisation. lru_cache's first argument is maxsize, the maximum size of the cache – here we've set it to None to indicate no maximum size.

Now if we try to use it:

>>> f(100)
573147844013817084101

And it didn't even take a second!

Note: f(1000) leads to a recursion depth error, but that's a story for another time

Factoid: I can define Jot with 2 upvotes, and prove that it's Turing complete with 8 (not using lengths 4, 6, or 7).

Length 1

1

This is an example of two functions in Jot. The first is the empty string, which evaluates to the identity function. The second is 1, which is Jot's grouping operator. 1 evaluates to λxy.[F](xy) (lambda calculus notation), where [F] is the program before the 1 (here, the empty string). So, this program is the function λxy.(λz.z)(xy) which simplifies to λxy.xy.

Length 2

10

Now we are introducing the other symbol in Jot: 0. Again if [F] represents the value of the program so far, 0 evaluates to [F]SK, where S and K are from combinatory logic. I've defined the entire language now.

Length 5

Length 8

11111000

This is the S combinator.

Length 3

1AB

Here, A and B are not part of Jot, but rather placeholders for an arbitrary expression. The expression AB in combinatory logic maps to 1AB in Jot, with A and B recursively transformed by these three rules. QED

Length N

1
10
11
100
101
110
[...]

Every natural number, expressed in binary, is a valid Jot program. Consequently, I can algorithmically generate more snippets of arbitrary length. Given enough upvotes, I can solve the halting problem.

APL

Factoid

APL (AProgramming Language) started out as an interpreter for a formula notation devised by Ken Iverson. When the language was designed, people used teletypwriters to communicate with computers. The character set of these was limited, but due to their construction, one could put multiple characters into the same position to compose complex characters. This feature is heavily used by APL, contributing to its infamous reputation as a read-only language.

Length 1

The character ⍝, called lampshade, both for its shape and for the enlightment you get from its presence, introduces a comment. Historically, it was created by overstriking a ∘ (jot) and a ∩ (up shoe).

Length 2

⍳3

The monadic (one argument) function ⍳ (iota) generates a vector of the first few natural numbers. For instance, the aforementioned ⍳3 would yield 1 2 3, the vector of the first three natural numbers. On some implementations of APL, it would yield 0 1 2 instead, this depends on the value of ⎕IO, the iota origin.

Length 3

5\3

As opposed to the monadic ⍳, the dyadic \ (expand) function copies the argument on the right as often as the argument on the left; thus, 5\3 yields 3 3 3 3 3. You might want to play around with vector arguments (like 1 2 3\4 5 6) to see what it does then.

Length 4

A←⍳3

This assigns to A the value of ⍳3. ← (left arrow) is the assignment operator. An assignment doesn't have to be the leftmost thing in a statement; assignments are parsed like function calls and yield the assigned value for further use.

Length 5

∘.×⍨A

A three by three multiplication table, that is,

1 2 3
2 4 6
3 6 9

This is a little bit complicated, so let me explain. ⍺∘.f⍵ (read: alpha jot dot f omega) is the outer product of ⍺ and ⍵ over f. The outer product is a table of the result of applying f to each possible pair of elements from ⍺ and ⍵. In this example, f is × (multiply), yielding a multiplication table. The operator ⍨ (tilde diæresis) commutes its arguments, that is, ⍺f⍨⍵ is equal to ⍺f⍵ and f⍨⍵ without a left operand is equal to ⍵f⍵. Without the commute operator this snippet would be a∘.×a. The outer product operator is very versatile; check out what happens if you substitute = for ×!

Length 6

{×/⍳⍵}

A factorial function. A pair of curly braces encloses a dfn (dynamic function), that is, an anonymous function (cf. lambda expressions). The arguments to a dfn are bound to the variables ⍺ and ⍵ or just ⍵ if the dfn is called as a monadic (single argument, as opposed to dyadic, two argument) function. We apply ⍳ to the right argument, yielding integers from 1 to ⍵. The / (slash) operator reduces, that is f/⍵ inserts f between the items of ⍵. For instance, +/⍳5 is just 1+2+3+4+5. In this case, we reduce with ×, yielding the product of the items of ⍳⍵, which is just the factorial of ⍵.

Length 7

2×3*4+5

Yields 39366. ⍺*⍵ (alpha star omega) is ⍺ raised to the power of ⍵. APL has a very simple precedence rule: Everything is evaluated from right to left, all functions are right-associative. Operators bind stronger than functions and are evaluates from left to right. Thus, the expression above with explicit parentheses would be written as 2×(3*(4+5)) as opposed to the usual (2×(3*4))+5.

Length 8

¯1+3 3⍴A

This snippet yields

0 1 2
3 4 5
6 7 8

and demonstrates two important concepts: The first concept is the ⍴ (rho) function, which reshapes its right argument to the shape specified in its left argument. The shape of an array is a vector of the lengths of each axis in the array. The shape of a scalar is the empty vector. Thus, 3 3⍴A reshapes A into a three by three matrix. The second concept is how addition is used here: We add ¯1 (overbar one), meaning negative one (¯ is a prefix to specify negative numbers, while - is an operator) to an array. The two operands have different shapes, so the operand with the lesser shape is distributed onto the other operand, subtracting one from every item in the generated matrix.

Length 9

+.×⍨3 3⍴A

A, reshaped to a 3 by 3 matrix, multiplied with itself. The . (dot) operator takes two functions and constructs an inner product, where the first function represents addition and the second function multiplication. A plain, old, matrix multiplication is +.×, a common variant is ≠.∧ (where ≠ is not equal and ∧ (up caret) is logical and) for boolean matrices; many interesting things can be modelled as an inner product with certain operators in place of + and ×.

Length 10

(.5×⊢+÷)⍣≡

(read: left parenthesis dot five multiply right-tack plus divide right parenthesis star-diæresis same) Compute the square root of a real using the Babylonian method. The left argument is the number you want to compute the square root of, the right argument is the initial guess for the square root. I originally wanted to provide a meaningful initial guess, but I ran out of characters (append ⍨ to use the number itself as the initial guess).

So how does this work? Let's start with the left part, (.5×⊢+÷), first. This expression uses tacit notation originating in J which was later ported back to Dyalog APL. Tacit notation is a bit hard for beginners, so please read this section carefully. An isolated sequence, such as +/÷≢, which the “normal” parsing rules do not resolve to a single part of speech is called a train. A train of two or three functions produces a function and (by repeated resolution), a function train of any length also produces a function. A train of three functions fgh behaves like {(⍺f⍵)g⍺h⍵}, that is, f and h are applied to the arguments of the resulting function and the result of these are applied to g. A train of an array and two functions like Afg behaves like {Af⍺g⍵}, this is, g is applied to the arguments of the resulting function and A and that result are applied to f. A train of two functions has a semantic, too, which is explained in the documentation but not used in this example.

In this particular train, one new function, ⊢ (right tack) is used. It behaves like {⍵}, yielding its right argument. Thus, the entire expression is equal to {.5×⍵+⍺÷⍵}, which is just the iteration step of the Babylonian formula. It is easy to see how tacit notation benefits the golfer; it allows you to shave of quite a few precious characters where applicable.

The last piece of the puzzle is the ⍣ (star diæresis), power operator. If the right argument is an array, f⍣A⍵ applies f to ⍵ a total of A times. For instance, f⍣3⍵ is equal to fff⍵. The count can be negative, in which case APL tries to infer an inverse function of f and applies that. If the right argument to ⍣ is a function, too, f⍣g⍵ applies f to ⍵ until (fY)gY where Y is the result of the repeated application of f to ⍵. Notably, if g is = (equal) or ≡ (same), f⍣≡ computes a fix point of f. This is exactly what we need for the Babylonian method! We want to iterate until the result converges. Lastly, if ⍣ applied to a pair of things is invoked as a dyadic function, the left argument is bound to f on the left, i.e. ⍺f⍣g⍵ is equal to (⍺∘f)⍣g⍵ where A∘f behaves like {Af⍵}.

Matlab

Snippet 26 - iterate over matrices

This is something I just recently discovered. Usually you iterate over a given vector in for loops. But instead of vectors, you can also use matrices (rand(10) produces a 10x10 matrix with uniformly distributed numbers between 0 and 1).

for k=rand(10);disp(k);end

This then displays one column vector of the random matrix per iteration.

Snippet 25 - easy plotting

We know plotting is easy in matlab, but there is a super easy function ezplot (E-Z get it? It took quite a while until I finally got it, as I spelled Z always as sed instead of c, whatever...) Everyone likes elliptic curves:

ezplot('y^2-x^3+9*x-10.3')

Snippet 24 - integration

The old fashioned word (but still in use in numerical computation) for integration is 'quadrature', can you guess what the result of the following one is?

quad(@(x)4./(1+x.^2),0,1)

Snippet 23 - images

Of course Matlab is also very popular among scientists who have to work with images (e.g. medical image analysis), so here is a very handy function. First argument is the image, second the angle and the third optional argument here tells the function to crop it to original size.

Snippet 22 - music

Snippet 21 - differentiate & integrate

You can easily differentiate and integrate polynomials by using those two functions. When integrating, you can pass a second argument that will be the constant.

Snippet 20 - back to polynomials

p=poly(r);cp=poly(A)

Want the polynomial with the roots in r? Easy: p=poly(r). Want the characteristic polynomial of a matrix A? Easy: cp=poly(A). So roots(p) is exactly r (or a permutation of r).

Snippet 19 - another magic trick

fminsearch(fun,x0);

There are people who absolutely love this function. This basically just searches a minimum of fun with an initial value x0 (can be a vector) without any conditions on fun. This is great for fitting small models where you cannot (or you are too lazy) to differentiate the error/penalty/objective function. It uses the Nelder-Mead simplex algorithm which is pretty fast for functions where you cannot make any assumptions.

Snippet 18 - intro to polynomials

p=polyfit(x,y,deg)

Matlab has a nice solution for coping with polynomials. With polyfit you get a least squares polynomial of degree deg that approximates the points in x,y. You get a vector p that stores the coefficients of the polynomials, because that is the only thing what you need for representing a polynomial. If you go back to snippet 15, you can do the same thing by writing c = polyfit(x,y,2). So e.g. [1,-2,3] represents the polynomial x^2 - 2*x+3.
Of course there are also functions for fitting other elementary, or arbitrary functions.

Snippet 17 - angles and discontinuities

unwrap(angle(c))

If you want to get the argument of a 'continuous' vector of complex numbers you often get back values that seem to have a discontinuity. E.g. angle([-1-0.2i,-1-0.1i,-1,-1+0.1i,-1+0.2i]) will get you [-2.94,-3.04,3.14,3.04,2.94] since angle only returns angles between -pi and pi. The function unwrap will take care of this! If you get a discontinuity like this, it will just add a multiple of 2*pi in order to remove those: '[-2.94,-3.04,-3.14,-3.24,-3.34]' This even works for 2d-matrices! If you just plot the argument of complex numbers with a negative real part you get the first graphics you'll get the first image, with unwrap you get the second one:

Snippet 16 - scalar product

[1;2;3]'*[4;5;6]

Of course there are built in methods (like dot), but with the matrix-transformation operator ' it is as simple as that. If you do not know whether you have row or column vectors, you can just use a(:)'*b(:) where a(:) always returns a column vector.

x is the (column) vector with the values on the x-axis, y the noisy y-values. Type c=[x.^2,x,x.^0]\y and you get the coefficients of the 2nd degree polynomial. Of course you can use one of the billion builtin fit functions of matlab (how boring) why not use the magic wand?=)

Snippet 14 - graphs

gplot(graph,x)

That is how to plot a graph. graph should contain a square adjacency matrix and x should be a nx2 matrix that contains the coordinates of each node. Lets make a random graph: graph = triu( rand(8)>.7) (make a Matrix that contains 0s and 1s, get only the upper triangle for an interesting graph). x = rand(8,2) then plot with some fancy styles gplot(graph,x,'k-.d')

(I declare this as modern art.)

Snippet 13 - meshgrid

meshgrid(a,b)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depending on two variables, you can just define a vector of values for the x-axis and one for the y-axis (a and b). Then with meshgrid, you can create two matrices of the size len(a) x len(b) where one has only the vector a as column, and the other has only the column has only the vectors b as rows. Usage example:a = -3:0.2:3;[x,y]=meshgrid(a) (if both vectors are the same, it is sufficient to just pass one.) Then you can just type z=x.^2+-y.^2 and e.g. mesh(x,y,z). This works for an arbitrary number of dimensions! So this is not only great for plotting, but also for getting all possible combinations of different vectors etc... (So, if you want to create a new code golf language, this should be in there, just make sure you use a shorter function name...)

Snippet 12 - plotting

plot(x,x.^2)

Take a vector x=-3:0.5:3 and and let plot do the rest. There are many more functions for plotting this is just a very basic one that you can use all the time. It would be already enough to write plot(v) and the data in v will be plotted against the array indices. How simple is that? If you want to style your plot, just add a string as a third argument: e.g. 'r:o' will make a red, dotted line with circles around the data points. If you want multiple plots, just add more arguments, or use matrices instead of vectors. Foolproof.

Snippet 11 - function handles

f=@(x,y)x+y

This is an example of a function handle that gets stored in f. Now you can call f(1,2) and get 3. Function handles in matlab are very useful for math functions (e.g. plotting) and you can define them in one line. But one drawback is that you cannot have conditionals or piecewise (and therefore no recursion). If you want this, you have to use the function statement and declare a new function, and each of those has to be stored in a separate file... (WHYYYYYY????)

PS: You'll get another funny easter egg if you type why in the console: They made a huge function that produces random messages like:

The tall system manager obeyed some engineer.
The programmer suggested it.
It's your karma.
A tall and good and not excessively rich and bald and very smart and good tall and tall and terrified and rich and not very terrified and smart and tall and young hamster insisted on it.

...which is very comforting if you are desperate enough to ask the console why...

Snippet 10 - How does my matrix look?

spy(eye(9))

As you know by now eye(9) creates a 9x9 identity matrix. spy just creates a that shows the zero/nonzero entries of the matrix. But you can also use it for displaying any binary 2d data. If you call spy without argument you'll get a nice little easter egg=)

Snippet 9

kron(a,b)

The kron function evaluates the Kronecker product of two matrices. This is very useful for discretisized multidimensional linear operators. I also used it every now and then for code golfing. You want all possible products of the entries of a and b? kron(a,b), here you go.

Snippet 8

5*a\b.*b

Ok here I mixed up 3 different operator. You can multiply any matrix by a scalar by just using *. (Then every entry of the matrix gets multiplied by that scalar). But * also performs matrix multiplications. If you prepend a dot you get the .* operator, this one multiplies two matrices of the same size but entry wise. (This can also be done with division operators like / and \.)

Next, the backslash operator can be used as left division (in contrast to / which performs right division as you are used to) but it is also the most powerful and characteristic operator of matlab: It performs a 'matrix division'. Lets say you have the system of linear equations A*x=b and you want to solve it for x, then you can just type x=A\b. And \ (you can also use / but that is less common for matrices) first quickly analyzes the matrix, and uses the results to find the fastest algorithm to perform this inversion-multiplication! (See e.g. here)

But you can also use it for under- or over-defined systems (where the there exists no inverse or where the matrix isn't even square, e.g. for least squares method). This really is the magic wand of matlab.

Snippet 7

[a,b;c]

Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expressions means that they get concatenated horizontally (that means they have to have the same height) and a semicolon means that the previous 'line' will be above the next 'line' (by line I mean everything between two semicolons. Just a simple example: a = [1,2;3,4]; b = [5;6]; c =[7,8,9]; d=[a,b;c]; will result in the same d as d=[1,2,5; 3,5,6; 7,8,9]. (Get it?)

Snipped 6

eye(7)

This function produces a full 7x7 identity matrix. It is that easy. There are other functions like nan,inf,ones,zeros,rand,randi,randn that work the very same way. (If you pass two arguments you can set the height/width of the resulting matrix.) As I will show later, you can easily create and (and in a very visual way) concatenate matrices (2d-arrays) which is sooo damn useful and easy if you have to numerically solve partial differential equations. (When you solve PDEs the general approach is discretisizig the derivative operators, basically you will get just a huge system of linear equations that needs to be solved. These matrices normally are sparse (only very few non-zero elements) and have some kind of symmetry. That's why you can easily 'compose' the matrix you need.

Snippet 5

a(a>0.5)

I hope you are not getting tired by all the ways of accessing arrays. This shows an easy way to get all elements of an array that meet some conditions. In this case you get a vector of all elements of a that are greater than 0.5. The expression a>0.5 just returns a matrix of the same size as a with ones for each element that satisfies the condition and a 0 for each element that doesn't.

Snippet 4

a(:)

This again just returns the contents of a as a column vector (nx1 matrix). This is nice if you do not know whether you stored your data as column or row vector, or if your data is two dimensional (e.g. for 2d finite differences methods).

Snippet 3

1:9

You can easily make vectors (in this case 1xn matrices) with the semicolon operator. In this case you get the vector [1,2,3,4,5,6,7,8,9]. This is also particularly nice for accessing slices of other vectors as e.g. a(2:4) accesses the second, third and fourth element of the vector a. You can also use it with a step size, like 0:0.5:10 or so.

Snippet 2

i;

A semicolon suppresses output to console. You can see it as a good or a bad thing, but I like it for debugging stuff. Any line of calculation etc. will automatically print its result to the console, as long as you do not suppress the output by a semicolon.

Snippet 1

i

Complex number are a basic number type. (Too bad many people use i as a counting variable in for loops in which case it gets overridden.)

Intro

For those who do not know, MatLab is a programming language (with nice IDE that is also called MatLab?) that is first of all intended for numerical calculations* and data manipulation. (There is an open source counterpart called "Octave") As it is only** interpreted it is not very fast, but it's strength are that you can easily manipulate matrices and many algorithms are implemented in an optimized way such that they run pretty fast when applied on matrices. It also is a very easy language to learn, but I do not recommend it as a starter language as you will assume pretty bad 'programming' habits.

*As it is a interpreted language it can be very slow for expensive projects, but you have built-in parallelization methods, and you can also use multiple computers together to run a program. But if you really wanna get fast I think you still depend on C or Fortran or crazy stuff like that. But still many implemented algorithms (matrix multiplication, solving systems of linear equations etc) are heavily optimized and perform quite well. But if you program the same algorithms in Matlab itself, you're gonna have to wait=) (Something really unintuitive when you come from other languages is that if you vectorize your operations instead of using for loops, you can save much time in Matlab.)

**You can sort of compile your programs, but that mainly converts the source code to an unreadable file (for humans), that is not that much faster when executed.

\$\begingroup\$@flawr - For the factoid, it may also be cool to mention the fact that historically, MATLAB was originally created for the students in Computer Science at the University of New Mexico (Cleve Moler was chairman at the time) as an easy interface to the LINPACK and EISPACK (... now being superseded by LAPACK) without having to learn FORTRAN.... and because of its ease of use, it spread to other academic institutions very quickly :)\$\endgroup\$
– rayryengJul 22 '15 at 20:01

Bash

Factoid:

The extremely serious ShellShock bug was present in Bash since 1989, and remained undiscovered for a quarter of a century. Much of the joy of writing Bash is coming to grips with its many idiosyncracies and inconsistencies.

Length 1 snippet:

[

An alias for the test builtin, allowing code of the format if [ a == b ]; then - in reality [ is a standalone command, not a syntactical element, and ] is purely decorative (although required by [, its requirement is arbitrary and you can do away with it by using alias [=test).

Length 2 snippet:

||

Like logical or in most languages, but for processes. Will execute the command after the || only if the command before it returns non-zero.

Length 3 snippet:

x=y

Assignment. Nice and predictable... but unlike most other languages, extra spaces aren't allowed. Which is kind of funny because you can stick extra spaces pretty much everywhere else between things in bash, just not around the =.

Length 4 snippet:

$IFS

Internal Field Separator - this variable affects how Bash splits data for many built-in actions, such as iterating in for loops and populating arrays from strings. Used correctly it can be very powerful; but more often it's the cause of subtle and unpredictable bugs.

Length 5 snippet:

${x^}

Substitute the string in x, but with the first character capitalised! Such a frequently used feature that it has its own dedicated piece of language syntax.

Length 6 snippet:

x=($y)

Fill an array, x, from a string or list of elements y, splitting on whatever the IFS is currently set to - by default, whitespace. A very useful feature for advanced bash programming.

Length 7 snippet:

${x[y]}

Arrays! But wait, what's that... y is a string, not a numerical index? Yes indeed, Bash supports associative arrays! Many people don't know this. You just need to declare -A x first.

Length 8 snippet:

${x##*,}

Substitute x, everything up until the last , character (or whatever you specify). Useful to get the last field of a csv - this is something you can't so easily do with cut, which only counts fields from the left. % and %% allows the same to cut from the right; % and # were chosen for their location on the US keyboard so it would be clear which means left and which means right, but that doesn't hold much value for everyone not using a US keyboard :)

Length 9 snippet:

[ a = b ]

In most other languages, a single equals in a comparison operation would produce unintended behaviour in the form of an assignment. Not in Bash, though. Just don't omit any of the spaces, whatever you do!

Length 10 snippet:

if [ a=b ]

This is what happens if you forget about the mandatory spaces. Will not throw an error. Will always return true - even if a and b are variables that are unset, or whatever they're set to, doesn't matter - it'll always return true. Think about code like if [ "$password"="$correctpass" ] to see the fun potential of this "feature".

Length 11 snippet:

x=${y//a/b}

Regex-style substring replacement! Set x to the value of y but with every instance of a replaced with b.

Length 12 snippet:

[[:upper:]]*

Pattern matching - you aren't limited to just using the * wildcard in the shell, you can use any POSIX standard match such as alnum, alpha, digit etc.

Length 13 snippet:

function x(){

A bit of C syntax has mysteriously crept in! One of many completely different uses for curly braces, and another example of optional decorative elements to make Bash look more like other languages - either () or function can be omitted here (but not both). Also more fun with inconsistent spaces - a space after the { is mandatory, but not before the closing }, as in function x { y;}

Length 14 snippet:

echo {Z..A..3}

Yet another totally unrelated use of curly braces. Expands a range with a specified step. In this case, will produce every 3rd letter from Z to A. Useful for generating sequences without using seq, but cannot be used with variables, so has limited functionality.

Length 15 snippet:

echo {a,b,c,d}x

Another similar but not identical use for curly braces in sequence generation; prints ax bx cx dx, and is useful for generating a list of strings from a sequence or list in a single command. Again however, limited in usefulness as it can't be used with variables inside the braces.

\$\begingroup\$Actually, ] is not purely decorative. [ will refuse to function if its last argument isn't ].\$\endgroup\$
– FUZxxlJan 26 '15 at 21:36

\$\begingroup\$Yes, but it serves no purpose other than cosmetics; and if you substitute [ with its other form test, then the ] can be omitted without changing anything else in the call - I'm simply making the point that it's not actual bash syntax, just visual sugar.\$\endgroup\$
– RiotJan 26 '15 at 21:39

\$\begingroup\$You're right in that it's not bash syntax, but the trailing ] is [ syntax and you have to provide it just like how you have to terminate a statement in C with a semicolon.\$\endgroup\$
– FUZxxlJan 26 '15 at 21:40

\$\begingroup\$It's true that it's mandatory, but not at all in the same way as the C semicolon. The requirement for it is entirely arbitrary, as seen if you simply alias [=test and then write if [ 1 = 1; then etc. But I'll clarify my wording to take your point into account :)\$\endgroup\$
– RiotJan 27 '15 at 0:15

1

\$\begingroup\$Regarding the function x(){ syntax: You can drop the parens, as you say, but you can also just drop the function part. In fact, that's how POSIX shell defines functions, so it's more portable that way. You could define a full function in 13 characters. For example: x(){ startx;}\$\endgroup\$
– kojiroJan 29 '15 at 2:02

CJam

The minmod function is a variant of the familiar min, which appears in slope-limiting high-resolution schemes for partial differential equations. Given a number of slopes, it picks out the flattest slope, while taking care of relative signs between the slopes.

The function takes an arbitrary number of parameters. Then minmod(x1, x2, ..., xn) is defined as:

min(x1, x2, ..., xn), if all xi are strictly positive

max(x1, x2, ..., xn), if all xi are strictly negative

0, otherwise.

Length 18 snippet:

l'[,65>Dm>_el+_$er

A ROT13 encoder. Shifts only a-zA-Z characters from the input string via STDIN

Length 15 snippet:

T1{_2$+}ri2-*]p

A full program to print the first N numbers from a Fibonacci series where N is provided as an input via STDIN.

Length 12 snippet:

{{_@\%}h;}:G

A simple GCD function. This can be used like 2706 410 G to get the GCD on stack.

Length 11 snippet:

123456 789#

# is the power operator. This snippet shows a cool feature of CJam that it supports BigInts for almost all mathematical operations. So the output of the above code is

One of the smallest possible quines in CJam. This is a true quine in a sense that it does not actually read the source code in any manner. (Reading the source code is not even possible in CJam)

Length 7 snippet:

"AB"_m*

m* creates all the Cartesian products of the top two stack elements. For instance, the above code will put ["AA" "AB" "BA" "BB"] on stack, which is the cartesian product of "AB" and "AB".

Length 6 snippet:

"_~"_~

A nice looking repeated code. DO NOT run this :) . This representation of code is the basis for the simplest quine in CJam. You put string "_~" on stack, make a copy (_) and evaluate it. Which in turns does the same thing again (and again ..) until you reach maximum recursion exception.

Length 5 snippet:

{A}:F

This is how a basic function works in CJam, The above expression assigns the code block {A} to variable F. Now in your code, you can put F anywhere to run the code block (and get 10 in this case)

Length 4 snippet:

"A"~

You can evaluate any code block or string or even a single character using ~. The above expression results to 10

Length 3 snippet:

Kmr

A typical random number generator from range 0 to K i.e. 20.

Length 2 snippet:

es

This gives the current timestamp (milliseconds from the epoch). CJam also has et for local time in a more usable format which returns an array comprising of the various parts of the current time ( day, hour etc).

Length 1 snippet:

A

CJam has almost all capital alphabets as predefined variables. A is 10, B is 11 and till K is 20. P is pi (3.141592653589793), N is new line and many others. These can come very handy when you need initial values in variables, or even when you need two digit number in 1 byte.

Factoid

CJam is inspired by GolfScript but builds a lot of features on top of it including support for a network GET call :D

PS: I will try to update the answer every 5 upvotes or every 2 hours (which ever is earlier)

\$\begingroup\$There are some issues with your ROT13 example :p But I'm impressed with the quine, I think I'll borrow it :)\$\endgroup\$
– aditsuFeb 1 '15 at 17:44

\$\begingroup\$@aditsu what is the issue ?\$\endgroup\$
– OptimizerFeb 1 '15 at 17:46

\$\begingroup\$It changes the case of n-z letters. Also, it has an @ for no reason, you can put the D there instead.\$\endgroup\$
– aditsuFeb 1 '15 at 17:49

\$\begingroup\$@aditsu Pretty sure that its a ROT 13 across a-zA-Z range and that is the reason for case change. Can you not read it ? its only your own language :P @ is there for 18 chars I guess :D\$\endgroup\$
– OptimizerFeb 1 '15 at 17:52

\$\begingroup\$That's not what ROT13 normally does. I don't understand why you're asking if I can read my own language, the issue is not about understanding what the program does, but about the fact that it doesn't do what's expected.\$\endgroup\$
– aditsuFeb 1 '15 at 17:54

Common Lisp

Lisp (from LISt Processing) is one of the oldest languages still in use today (only FORTRAN is older). It is notable for being the first language where code is data and data is code; called homoiconicity. It was also the first language to have garbage collection. Originally designed by John McCarthy in a 1958 paper as an entirely theoretical language, it became a real language when Steve Russel realized that the eval function could be implemented on a computer. It's most prevalent in Artificial Intelligence, and is instantly recognizable from its preponderance of parentheses. Common Lisp was designed to unify many of the older Lisp dialects into a more standardized form.

I'll be trying for every snippet to be runnable on it's own, though not necessarily do anything of value. Additionally, because I'm using Common Lisp, the fundamental concepts and a lot of the syntax apply in other dialects, but certain functions won't work in, say, Scheme.

Length 1

*

Because of the emphasis on the use of S-Expressions and lists for coding, there're very few valid expressions in Lisp that don't contain parentheses, called atoms. Anything typed directly into the REPL (read-eval-print loop) is treated as a variable and evaluated as such. * holds the previous value that was printed by the REPL.

Length 2

()

This is the empty list, one of the most important symbols in Lisp. Every proper list in Lisp is terminated with an empty list, similar to how every proper string in C ends with \0.

Length 3

(*)

This is a basic function call, which consists of a symbol wrapped in parentheses. Lisp doesn't contain operators, they're just functions too. I picked multiplication specifically because it's not actually a binary function; the multiplication operator in Lisp takes an indefinite number of arguments. If it is given no arguments it returns 1, the identity operator for multiplication.

Length 4

`(1)

This is a cons cell, which is just another way of saying it's a pair of elements. In Lisp, each list consists of cons cells connected to cons cells, where the first element (the car) is the value and the second element (the cdr) points to the next cons cell. This forms the basis of Lisp being based upon linked lists. This particular cons cell has 1 as the car and the empty list as its cdr.

Length 7

(not t)

I want to touch on truth values in Lisp. This would return nil. In Common Lisp, t is the symbol for true while nil and () represent false and are equal to each other, but note that this definition isn't standard for all Lisp dialects; Scheme, for example, distinguishes between #f for false and '() for the empty list.

Length 9

(cdr ())

As I said before, the cdr is the tail element of a list, which you can get with the function cdr. Likewise, you can get the head element, the car, with the function car. Pretty simple, right? The car and cdr of the empty list are both nil.

Length 10

(cons 1 2)

Finally, enough length to start working with lists. cons creates a cons cell with the first parameter as the car and the second as the cdr. But instead of printing out (1 2), it gives (1 . 2). Going back to the length 2 snippet, a proper list is supposed to end with the empty list, so the cdr of the last cons cell should point to the empty list. In this case, the last cons cell points to 2, so Lisp informs us that we have an improper list, but still allows us to do it, like how you can make a C-string without a \0.

Length 11

(cons 1 ())

Now we have created our first properly formed list. It's a single cons cell with a car of 1 and a cdr of (). You'll notice that for every other list, I lead it with a backquote/tick; any other proper list would attempt to evaluate its first argument as a function with the remaining elements as parameters. Strictly speaking, () isn't a list though; it's a symbol composed of a ( and a ) that represents the empty list. Lisp allows you to use almost any printable character in a symbol name and will let you redefine any symbol as you want to.

Length 12

(cdr `(1 2))

This would output (2), not 2 as some people would guess. Remember, each cdr is supposed to point to either another cons cell or the empty list; obviously 2 isn't the empty list, so it must be another cons cell the a car of 2 and a cdr of ().

Length 13

'#1=(1 . #1#)

This would produce a circular list with just the single value 1. If printed, it would print “(1 1 1 1 ...” forever, so that in practice it can be considered an infinite list (on which you can do cdr infinite times to obtain always the same result, itself!). Unless one assigns T to the global variable *print-circle*, in which case it will be printed as #1=(1 . #1#).

GNU Make

Factoid

Length 0 snippet

I don't think length 0 snippets are required, but here is one anyway. I think this might be the most useful of all length 0 programs. With an empty Makefile (or even no makefile at all), make still has a bunch of built-in rules. E.g. there are default built-in rules to compile a .c file into a .o or binary, given the .c file exists in the current directory. So if we do:

make hello.o

make will find the .c to .o rule and compile hello.c to give hello.o

Similarly if we do:

make goodbye

If there is a goodbye.c file in the current directory it will be compiled into the goodbye binary.

Length 1 Snippet

TAB

Yes, the TAB character. While this doesn't do much on its own, it has great significance in Make. Specifically all recipe lines following a target definition in a rule MUST start with a TAB. This causes all sorts of frustrations when debugging makefiles when TABs and spaces get mixed up.

Length 2 Snippet

Length 3 Snippet

a:=

Shortest simply expanded variable assignment. The variable a is set to "" immediately when the Makefile is first parsed. If instead we do a=, then the assignment is recursively expanded, i.e. expansion is deferred until the time the variable is actually referenced.

Length 4 Snippet

This is an alternative rule syntax in that the recipe follows the target on the same line separated by a new line. More commonly the recipe lines immediately follow a separate target line, with TAB characters starting each recipe line.

Length 5 Snippet

$(@D)

Another automatic variable. Similar to $@, but this expands to the directory portion of path, with the filename and trailing / removed.

Marbelous

Length 14 snippet

}0}1
Mulx
HxHx

This snippet shows off some more of Marbelous libraries and introduces a new concept, namely, multi-cell boards. The Mulx board takes two marbles as input and outputs 2 marbles. Marbles that enter the leftmost cell of the Mulx will correspond to the }0 devices in that board and the rightmost cell to }1. Analogously, the outputs will come out of different cells as well. The width of a board can be calculated as MAX(1, highest output device + 1, highest input device + 1) cells that don't correspond to an input device will trash any marble that falls upon them.

Length 13 snippet

7E
??
>Y!!
{0

This is a board that will spit out a random printable ascii character on each tick. Marbelous has two ways of generating random values. There is ?? which returns a random value between 0 and the input marble it receives, inclusive, and ?n: ?0 up to ?Z respectively. Which act very similar to ??. We also have !! which terminates the board even if not all outputs are filled. Can you figure out how the ?n devices could be implemented as boards in Marbelous using ???

Length 12 snippet

}0}1
Fb//
Dp

Here we see a few library functions of Marbelous in action.
Fb outputs the nth fibonacci number where n is the input marble. Dp prints the input marble to STDOUT as a decimal number. These are both implemented in Marbelous and can be called upon when you check include libraries in the online interpreter, for the python interpreter, you have to explicitely include each file. The inplementation of these boards can be found on github. Note that this particular program takes 2 inputs and will call the Fibonacci board two times. Boards that are called are return within one tick of the board that called them.

Length 11 snippet

}0}0
{<{0{>

This one needs some explanation. The }0 devices are imputs, since they have the same number (0), they will contain the same value when this board gets called. The three devices on the lower row are outputs. {< outputs to the left of the board, {0 outputs underneath the first cell of the board and {> outputs to the right. Output is only pushed when all distinct output devices are filled. In this case however, the right output device is never reached. The board will exit because of lack of activity and output the two values it has anyway. Can you imagine how one could implement /\ as a Marbelous board?

Length 10 snippet

..40
FF
\\

There's a few things that play an important role in Marbelous here. Firstly, there's addition. If you trace the path of the two marbles on the board, you'll notice that they'll end up on the same cell at the same time. When this happens, they'll be added together. (fun fact: at some point it was considered that instead of being added together, the marbles should form a stack) However, Marbelous is an 8 bit language, So adding a marble to FF is equivalent to subtracting 1 from it.

Length 9 snippet

00
\\/\]]

This is the shortest way to implement a rudimentary version of cat in Marbelous.
00
\/\
Is a loop that puts a 00value marble on the ]] device every second tick. This is an STDIN device. When a marble lands on this device, it tries to read the first character from STDIN, if there is one, it gets pushed down (and in this case printed again). If there isn't one, The original amrble gets pushed to the right. (and in this case trashed)

Length 8 snippet

}0
~~
{0

This snippet shows a few features. Firstly it takes input through }0. In this case this is the Main Board and this will be replaced by the command line input. You can also call this function, in that case, the argument will be taken instead of the command line input. Then there's ~~, which is a bitwise not operator. After that, we get to }0, If all }n devices are filled, these values are returned as the functions return values. (Marbelous supports more than one return value per function)

Length 7 snippet

00
\\/\

This is the most compact infinite loop you can create in Marbelous. The \\ device pushes any marble to the right, /\ copies a marble and pushes one copy to the left and another to the right. Since the board is only two cells wide, the marble to the right gets trashed though.

Length 6 snippet

46MB75

Here's an example of recursion, MB (the implicitly named main board gets called on every tick, but not before Printing Fu to STDOUT on each call. (Resulting in the following: FuFuFuFuFuFu... This obviously overflows the callstack.

Length 5 snippet

2A
++

Some arithmetic, The marble with value 2A falls down on teh first tick and the finds itself on the ++ cell. This is an operator. This particular operator increments any marble that land on it and lets it fall down. The marble now has value 2B and falls off the board. This prints + to STDOUT.

Length 4 snippet

:
24

The two interpreters disagree here, I've given the first board of the file a name in this example (The name is an empty string). The python interpreter assumes this is the Main board and calls this board upon running the program (which prints $). The javascript interpreter doesn't find the Main Board and thus no entry point. This can be useful when writing a library file for Marbelous.

Length 3 snippet

:Bo

This is a named board, with no body, we can call this board by Writing Bo in a cell of any board (including Bo itself)

Length 2 snippet

3A

This code is the body of a 1x1 cell (each cell is two characters wide) board, implicitly named MB (for Main Board). It prints the ascii value of the hexadecimal value of 3A when the marble falls off the board. The output of this program just so happens to be the source code of:

Length 1 snippet

:

Along with #, this is one of the two the only valid 1 character programs in marbelous. # is an indicator of a comment an therefor not very interesting. : tells marbelous that you're about to declare a board. Neither of teh two compilers care that you don't actually name or define the board. The program doesn't do anything.

factoid:

Marbelous was developed by people on this site, some names that were in the running for this language were Rube and simply Marbles.

Forth

Forth has only two types, ints and floats (and the floats are optional!) but it still manages to have chars, strings, long long ints, pointers, function pointers, structs, and more; it's all in how you use it!

Length 1

.

The . command (or "word" as we call it) prints out the integer value on top of the data stack; if the stack is empty, you get a runtime error. It also remove the value from the stack — upvote to see how we can keep it!

Length 2

.s

The .s word displays the values currently on the stack, without removing any of them. It also displays the total number of values. In Gforth, .s is limited by default to only showing the top 9 values; maybe we'll find out how to show more?

Length 3

see

Type see followed by any Forth word to see that word's source code. Most Forth words are defined in Forth itself, and only a few primitives are defined in assembly.

Length 4

1 0=

Did I mention that Forth is a stack-based language with postfix operators? Typing 1 0= pushes 1 onto the stack and then executes the 0= word, which pops the top value off the stack and pushes true if it equals 0, false if it doesn't. 0= is a convenience word for 0 =; there are several shorthand words like it for common value+word combinations, like 1+ and 0<>. Moreover, while false in Forth is 0 and any nonzero value is true, the built-in test words return true for true results, and true goes all the way — it's the value with all bits set, i.e., -1!

Length 5

-1 u.

Push -1 onto the stack, then pop it off and print it as an unsigned integer. This can be used to quickly see the maximum value for an unsigned int on your version of Forth (but not the maximum integral value that it natively supports!). You may be asking, "How do we know when an int should be printed with . and when with u.?" Answer: . when it's signed, u. when unsigned. "That's not what I meant," you say. "How do we know when the value on top of the stack is signed and when it's unsigned?" Answer: You're the programmer — that's your job! You have to know whether each integer on the stack represents an int, an unsigned int, an int*, a char*, a function pointer, or other, or else you get the demons in your nose. Forth's not going to keep track of that for you; what is this, C?

Length 6

." Hi"

Prints Hi. ." is a Forth word (which, like all Forth words, must be followed by whitespace or EOF) that reads the input stream up through the next " and prints out any bytes in between. If you put more than one space after the .", all but the space immediately after the ." will be printed. Escape sequences are not supported (so you can't print a string with a " in it with ."), but Gforth adds .\" to the language, which does support them.

Length 7

: + - ;

You define your own words in Forth by writing a colon, the name of the word, the words that you want your word to execute, and a semicolon. A word can be any sequence of non-whitespace characters (whitespace is how Forth tells where one word ends and another begins, after all), even punctuation, and even operators (which are just words, after all). The above snippet redefines + to mean -, so now whenever you try to add, you subtract instead. Any pre-existing words that use + are unaffected, as they store a reference to the original definition of +.

Note: Some words do different things inside definitions of other words than they do outside, but other than control structures, they're all pretty esoteric. Most words do the same thing inside a definition as outside, but sometimes that thing isn't obvious — : show-see see see ; won't do what you think!

Length 8

: 42 - ;

When I said a word could be any sequence of whitespace characters, I meant any sequence. No, Forth does not have a word for each individual number; numbers are just a little special. When Forth encounters a non-whitespace sequence, it first sees if it's a known word; if it's not, it tries to parse it as a number; if that fails, only then do you get an error. Defining a word that's spelled the same as a number means that you won't be able to enter that spelling of the number directly anymore without getting the word instead, but Gforth and various other Forths give you multiple ways to spell numbers anyway.

Length 9

IF 1 THEN

Finally, something familiar! Obviously, this code tests whether its argument 1 is true and, if so, executes whatever's after the THEN, right? Wrong. When execution reaches the IF, the value on top of the stack is popped off, and if that value is true (i.e., nonzero), execution continues with whatever's inside the IF ... THEN and then whatever's after the THEN; if the value is zero, we just skip straight to after THEN. Note that, due to how these words are implemented internally (which is in terms of other Forth words!), IF and THEN can only be used inside a word definition, not in "interpret state."

Length 12

( x y -- y )

This is a comment. It goes from the ( to the next ) immediately after it. (In the interpreter, a newline can also end it.) This is not "built in" to Forth's syntax (Is anything?); ( is just another word, one that discards everything in the input stream up through the next ). (That's right — Forth can manipulate how its source code is read. Perl's not the only language that can't be parsed without executing it!) Since it's a word, you have to follow it with a space, or else Forth will complain that (x is undefined. We can also redefine ( as part of our ongoing campaign of shooting ourselves in the foot.

The comment's content is more interesting, however. This comment specifices the stack effect for some word; the part to the left of the -- lists what should be on the top of the stack before you run the word (the top is on the right), and the right side of the -- describes what the top of the stack will look like afterwards (again, the top is on the right). Common convention is to add such a comment to the source of any word you define, right after the : name bit, and there is also a very strong convention about naming stack elements to indicate their type that is even followed by the standard.

Incidentally, the stack effect shown is for the nip word. You should be able to tell what it does just from the comment.

Length 13

1 2 3 4 d+ d.

As previously indicated, a Forth value's type is all in how you use it — if you treat a value as a pointer, it's a pointer, and if that value's not a good pointer, it's your fault for treating it as one. However, regardless of what type you're treating a value as, it will always take up one cell on the data stack; the exceptions are double cell or double precision integers. These are integers that are represented by two values on the stack, allowing you to perform arithmetic with twice as many bits as usual. The more significant or higher-bit cell is placed on top of the less significant or lower-bit one, so that 1 0 is the double cell representation of 1, and 0 1 is either 2^32 or 2^64, depending on how big your Forth's regular cells are. Naturally, in order to treat a double-cell value as such, we need to use words that explicitly operate on double-cell values; these are generally just d (or ud for unsigned) followed by the name of the corresponding single-cell word: d+ for addition, d< for comparison, d. for printing, etc.

IBM Enterprise COBOL

Factoid: Whilst it is possible (twists and turns) to have a useful two-character program (to be the target of a CALL to a sub-program which doesn't otherwise exist yet), other than variations of the same thing, the next one would come in at 26 characters, and would be a variation which... doesn't work.

Plus that is not counting the mandatory seven blanks at the start of a line. And it would be severely abusing the language.

COBOL's not really so good for this challenge.

This is becoming interesting in itself. Although it will be a while before I can get the program to do something else, it is an interesting academic voyage of discovery.

Remembering that these are short, and abused, programs it is interesting that only valid COBOL can be ignored, if invalid it gets an S-level diagnostic, which is going too far. Some actually valid COBOL will not work without a full-stop/period, as I've noticed when trying to Golf(!) things previously.

Two characters

Excellent. Here's the two-character example. Remembering, sorry about that, that it must be preceded by seven blanks.

ID

Doesn't look like much of a program. Certainly not much of a COBOL program. You do have to bend things a little.

Compile it, and these are the diagnostic messages you get:

1 IGYDS1102-E Expected "DIVISION", but found "END OF PROGRAM".
"DIVISION" was assumed before "END OF PROGRAM".
1 IGYDS1082-E A period was required. A period was assumed
before "END OF PROGRAM".
Same message on line: 1
1 IGYDS1003-E A "PROGRAM-ID" paragraph was not found.
Program-name "CBLNAM01" was assumed.

That gets you a Return Code/Condition Code of eight. Normally you wouldn't generate the code for, or attempt to execute, a program with an RC/CC higher than four. However, none of those messages affect the generated code (except the allocation of a Program-name).

What does the program do? When it is CALLed, it simply returns to where it was called from, in the normal manner.

How would you use it?

Whilst developing a program, you want to check out the control flow, but you haven't written a couple of the sub-programs yet. Simply copy the loadmodule (created by feeding the object code produced into the linkeditor/binder) to the name of the CALLed program and, assuming you are using Dynamic CALLs, you have a stub which is just going to give you back control. For a Dynamically-called program, the PROGRAM-ID (Program-name) is irrelevant, so it does not matter if you accept the generated name.

An equivalent "real" program would be this.

ID DIVISION.
PROGRAM-ID. Anything.

Alternate two-character (didn't know about this before)

FD

Diagnostics

IGYDS1000-E A "IDENTIFICATION DIVISION" header was not found
in this program. It was assumed present.
IGYDS1003-E A "PROGRAM-ID" paragraph was not found.
Program-name "CBLNAM01" was assumed.
1 IGYDS1022-E A data-name or file-name definition was found
outside of the "DATA DIVISION". Scanning was
resumed at the next area "A" item or the start of
the next entry.
1 IGYSC1082-E A period was required. A period was assumed
before "END OF PROGRAM".

Note the lack of line-number for the first two messages. This time, with an ID, there is no line-number to associate those messages with.

Three characters also didn't know

1 A

Diagnostics

IGYDS1000-E A "IDENTIFICATION DIVISION" header was not found
in this program. It was assumed present.
IGYDS1003-E A "PROGRAM-ID" paragraph was not found.
Program-name "CBLNAM01" was assumed.
1 IGYDS1022-E A data-name or file-name definition was found
outside of the "DATA DIVISION". Scanning was
resumed at the next area "A" item or the start of
the next entry.
1 IGYSC1082-E A period was required. A period was assumed
before "END OF PROGRAM".

This program defines a group-item (valid for this purpose) but it is discarded.

Program operates as above.

Four characters

Since it is COBOL, we should see a full-stop/period at some time. Now.

1 A.

Even though the line is discarded, it gets one less diagnostic because the program source now ends with a full-stop/period.

Five characters

We're up to five votes, so here's a five character program that is equivalent:

ID FD

This operates in exactly the same way as the two-character example. FD is valid COBOL, so the compiler realises there is some stuff missing. Without it being valid COBOL, there would be an S-level message, and an RC/CC of 12. With it being a valid COBOL word, but obviously out of place, the third messages shows that it is just ignored.

1 IGYDS1102-E Expected "DIVISION", but found "FD". "DIVISION"
was assumed before "FD".
1 IGYDS1082-E A period was required. A period was assumed
before "FD".
1 IGYDS1022-E A data-name or file-name definition was found
outside of the "DATA DIVISION". Scanning was
resumed at the next area "A" item or the start of
the next entry.
1 IGYDS1003-E A "PROGRAM-ID" paragraph was not found.
Program-name "CBLNAM01" was assumed.
1 IGYSC1082-E A period was required. A period was assumed
before "END OF PROGRAM".

Six characters

ID 1 A

Combining a two character and a three characters, which need to be separated.

Diagnostics similar to the five-character solution.

Seven characters

LINKAGE

That's a reserved-word used (followed by the word SECTION) to identify the data-items which are defined elsewhere and whose addresses are made available by a CALL from another program. Its inclusion doesn't affect our existing program :-)

Diagnostics

IGYDS1003-E A "PROGRAM-ID" paragraph was not found.
Program-name "CBLNAM01" was assumed.
1 IGYDS1000-E A "IDENTIFICATION DIVISION" header was not found
in this program. It was assumed present.
1 IGYDS1005-E The "DATA DIVISION" header was not found. A
"DATA DIVISION" header was assumed before "LINKAGE".
1 IGYDS1103-E Expected "SECTION", but found "END OF PROGRAM".
"SECTION" was assumed before "END OF PROGRAM".
1 IGYDS1082-E A period was required. A period was assumed
before "END OF PROGRAM".
Same message on line: 1

A little more interesting this time. That "Same message on line: 1" looks odd (as the other message it is the same as is also line 1) but that is because we only have a one-line program and there are two required full-stops/periods (should be one after the SECTION which isn't there and one to end the source program).

Your Answer

If this is an answer to a challenge…

…Be sure to follow the challenge specification. However, please refrain from exploiting obvious loopholes. Answers abusing any of the standard loopholes are considered invalid. If you think a specification is unclear or underspecified, comment on the question instead.

…Try to optimize your score. For instance, answers to code-golf challenges should attempt to be as short as possible. You can always include a readable version of the code in addition to the competitive one.
Explanations of your answer make it more interesting to read and are very much encouraged.

…Include a short header which indicates the language(s) of your code and its score, as defined by the challenge.

More generally…

…Please make sure to answer the question and provide sufficient detail.

…Avoid asking for help, clarification or responding to other answers (use comments instead).