Notes

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

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

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

How this works

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

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

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

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

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

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

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

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

Current answers, sorted alphabetically by language name

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

225 Answers 225

up vote 404 down vote
+50

Mathematica

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

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

Length 143 and 144 snippets

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

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

It's quite unreadable, because I had to golf it down a lot:

d=θ@t-φ@t;NDSolve[{#''@t==-#4#2''[t]Cos@d-##3#2'@t^2Sin@d-Sin@#@t&@@@{{θ,φ,1,.5},{φ,θ,-1,1}},θ@0==2,φ@0==1,θ'@t==φ'@t==0/.t->0},{θ,φ},{t,0,60}]

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

enter image description here

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

Graphics@{Line@{{0,0},p=θ~(h={Sin@#@#2,-Cos@#@#2}&)~t,p+φ~h~t},White,{0,0}~Circle~2.2}~Show~ParametricPlot[θ~h~u+φ~h~u,{u,0,t}]~Animate~{t,0,60}

The resulting animation looks like this:

enter image description here

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

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

Length 100 snippet

GeoGraphics[{GeoStyling[Opacity[0.5]], NightHemisphere[]}, GeoBackground -> GeoStyling["ReliefMap"]]

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

enter image description here

Length 81 snippet

CellularAutomaton[{{0,2,3,If[0<Count[#,1,2]<3,1,3]}[[#[[2,2]]+1]]&,{},{1,1}},i,n]

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

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

enter image description here

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

ListAnimate[ArrayPlot[#,ColorRules->{0->Black,1->Blue,2->Red,3->Yellow}]&/@w]

Length 69 snippet

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

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

{{R[r] -> 1/2 r^(-(1/2) - Sqrt[5]/2) (1 - Sqrt[5] + r^Sqrt[5] + Sqrt[5] r^Sqrt[5])}}

which could now be easily used for further computations or plotted.

Length 64 snippet

CellularAutomaton[{224,{2,{{2,2,2},{2,1,2},{2,2,2}}},{1,1}},i,n]

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

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

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

enter image description here

Length 59 snippet

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

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

enter image description here

Length 52 snippet

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

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

enter image description here

Length 48 snippet

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

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

Length 45 snippet

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

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

enter image description here

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

enter image description here

Length 44 snippet

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

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

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

enter image description here

Length 43 snippet

HighlightGraph[graph,FindVertexCover@graph]

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

enter image description here

Length 42 snippet

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

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

enter image description here

Length 40 snippet

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

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

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

Length 39 snippet

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

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

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

Length 37 snippet

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

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

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

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

Length 36 snippet

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

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

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

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

Length 35 snippet

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

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

enter image description here

Length 34 snippet

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

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

{
  {x -> 0}, 
  {x -> -(b/(3 a)) - (2^(1/3) (-b^2 + 3 a c))/(3 a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) + (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)/(3 2^(1/3) a)}, 
  {x -> -(b/(3 a)) + ((1 + I Sqrt[3]) (-b^2 + 3 a c))/(3 2^(2/3) a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) - ((1 - I Sqrt[3]) (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3))/(6 2^(1/3) a)}, 
  {x -> -(b/(3 a)) + ((1 - I Sqrt[3]) (-b^2 + 3 a c))/(3 2^(2/3) a (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3)) - ((1 + I Sqrt[3]) (-2 b^3 + 9 a b c - 27 a^2 d + Sqrt[4 (-b^2 + 3 a c)^3 + (-2 b^3 + 9 a b c - 27 a^2 d)^2])^(1/3))/( 6 2^(1/3) a)}
}

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

Length 33 snippet

Dynamic@EdgeDetect@CurrentImage[]

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

Length 32 snippet

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

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

enter image description here

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

Length 28 snippet

Graphics3D@{Sphere[],Cone[]}

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

enter image description here

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

Length 27 snippet

CountryData["ITA", "Shape"]

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

enter image description here

Length 26 snippet

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

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

enter image description here

Length 25 snippet

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

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

{53, 43, 92}

Length 23 snippet

Rotate[Rectangle, Pi/2]

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

enter image description here

Length 22 snippet

30~ElementData~"Color"

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

SlateGray

Length 21 snippet

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

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

1/2 Sqrt[π] Erf[x]

Length 20 snippet

"Sun"~StarData~"Age"

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

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

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

which is displayed as

enter image description here

Length 19 snippet

MandelbrotSetPlot[]

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

Mathematica graphics

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

Length 18 snippet

PetersenGraph[7,2]

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

Mathematica graphics

Length 17 snippet

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

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

Mathematica graphics

Length 15 snippet

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

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

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

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

We would get

{4,5,1,2,3}

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

Length 12 snippet

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

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

x^y^x (y^(-1 + x) + y^(-1 + x) Log[x] + x y^(-1 + x) Log[x] Log[y]) + 
  x^(1 + y^x) y^(-1 + x) Log[x] (y^x/x + y^x Log[x] Log[y])

Length 9 snippet

Exp[I*Pi]

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

Length 8 snippet

Sunset[]

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

enter image description here

Length 7 snippet

9!/43!!

This snippet shows off a few cool things.

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

128/198893132162463319205625

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

Length 4 snippet

Here

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

Length 3 snippet

x-x

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

Length 2 snippet

3x

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

Length 1 snippet

π

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

Factoid

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

  • 17
    Snippet 23 is quite curious. If you did Translate[Scale[Rectangle, 80], {0, 0, 100}] would the huge word Rectangle appear floating in front of your monitor? – Calvin's Hobbies Jan 19 '15 at 20:41
  • 50
    @Calvin'sHobbies Just tried it... picked an unfortunate z offset... smacked me right in the face. – Martin Ender Jan 19 '15 at 20:44
  • 44
    The official Mathematica website should absolutely link to this. – Caridorc Jan 21 '15 at 20:48
  • 7
    @durron597 By keeping it as a symbol and making all your trigonometric and complex functions aware of what to do with a π. – Martin Ender Jan 22 '15 at 17:44
  • 16
    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. – Alex A. Jan 23 '15 at 16:41

The Infamous Shakespeare Programming Language

Shakespeare Programming Language was created in 2001 by two Swedish students, Karl Hasselström and Jon Åslund, and it combines, as the authors proclaim,

the expressiveness of BASIC with the user-friendliness of assembly language.

Answers go from top to bottom. Also, it's common to see me refer to older or previous snippets.

(link for myself: edit)

Factoid:

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

Length 1 snippet:

I

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

Length 2 snippet:

as

Used in a comparative between two "characters".

Length 3 snippet:

day

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

Length 4 snippet:

rich

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

Length 5 snippet:

Act I

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

Length 6 snippet:

better

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

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

Length 7 snippet:

Juliet:

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

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

Length 8 snippet:

[Exeunt]

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

Length 9 snippet:

as bad as

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

Length 10 snippet:

difference

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

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

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

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

Length 11 snippet:

[Exit Romeo]

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

Length 12 snippet:

Remember me.

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

Length 13 snippet

Let us return

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

Length 14 snippet

my little pony

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

Length 15 snippet

Speak thy mind!

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

Length 16 snippet

You are nothing!

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

Length 17 snippet

Ophelia, a wench.

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

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

Length 18 snippet

lying sorry coward

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

Length 19 snippet

Romeo:
 Remember me.

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

Length 20 snippet

cube of thy codpiece

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

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

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

Length 21 snippet

Listen to your heart.

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

Length 22 snippet

Recall your childhood!

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

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

Length 23 snippet

Are you better than me?

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

Length 24 snippet

[Enter Romeo and Juliet]

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

Length 25 snippet

remainder of the quotient

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

Length 26 snippet

Let us return to scene II.

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

Length 27 snippet

[Exeunt Ophelia and Hamlet]

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

Length 28 snippet

Scene I: Ophelia's flattery.

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

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

Length 29 snippet

You pretty little warm thing!

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

Length 30 snippet

You are as cowardly as Hamlet!

Saying this to, per instance, Romeo, means that Romeo = Hamlet. Like snippet 9.

Factoid (yes, another landmark reached!)

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

Length 31 snippet

Am I as horrid as a flirt-gill?

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

Length 32 snippet

If so, let us return to scene I.

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

Length 33 snippet

If not, let us return to scene I.

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

Length 34 snippet

Open your mind! Remember yourself.

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

Length 35 snippet

Act I: Death!

Scene I: Oh, shit.

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

Length 36 snippet

Thou art as sweet as a summer's day!

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

Length 37 snippet

Art thou more cunning than the Ghost?

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

Length 38 snippet

[Enter the Ghost, Romeo and the Ghost]

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

Length 39 snippet

the sum of a fat lazy pig and yourself!

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

Length 40 snippet

the sum of a squirrel and a white horse.

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

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

SPL, in its version 1.2.1, can be downloaded here.

Length 41 snippet

Juliet:
 Speak thy mind!

[Exit Romeo]

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

Length 42 snippet

Speak YOUR mind! You are as bad as Hamlet!

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

Length 43 snippet

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

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

Length 44 snippet

You are as evil as the square root of Romeo!

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

Length 45 snippet

Hamlet:
 Art thou more cunning than the Ghost?

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

Length 46 snippet

the product of a rural town and my rich purse.

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

Length 47 snippet

Romeo:
 Speak your mind.

Juliet:
 Speak YOUR mind!

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

Length 48 snippet

You lying fatherless useless half-witted coward!

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

Length 49 snippet

Scene V: Closure.

Hamlet:
 Speak your mind!

[Exeunt]

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

Length 50 snippet

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

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

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

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

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

Length 51 snippet

Othello:
 Recall your great dreams. Speak your mind!

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

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

Length 52 snippet

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

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

Length 53 snippet

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

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

Length 54 snippet

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

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

Length 55 snippet

Juliet:
 You are as lovely as the sweetest reddest rose.

So, here, Juliet is praising the "character" she's speaking to (let's assume it's Romeo, for Shakespeare's sake), declaring that he/she is 4. Yes, another assignation of values.

Length 56 snippet

Othello:
 You lying fatherless useless half-witted coward!

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

Length 57 snippet

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

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

Length 58 snippet

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

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

Length 59 snippet

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

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

Length 60 snippet

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

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

Length 61 snippet

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

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

Length 62 snippet

twice the difference between a mistletoe and a oozing blister!

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

Length 63 snippet

You lying stupid fatherless rotten stinking half-witted coward!

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

Length 64 snippet

your coward sorry little stuffed misused dusty oozing rotten sky

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

Length 65 snippet

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

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

Length 66 snippet

You are as beautiful as the difference between Juliet and thyself.

So, subtract Juliet from yourself, heh? This one's pretty simple to decode: Romeo=Juliet-Romeo;, assuming it's Romeo who's being spoken to.

Length 67 snippet

Juliet:
 Am I better than you?

Romeo:
 If so, let us proceed to Act V.

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

Length 68 snippet

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

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

Length 69 snippet

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

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

Length 70 snippet

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

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

Length 71 snippet

Scene I: Dialogues.

[Enter Juliet]

Othello:
 Speak your mind!

[Exit Juliet]

A Scene can be as small as this. Juliet enters the stage, Othello tells her to output her stored value, then she gets off stage again.

Length 72 snippet

twice the difference between a mistletoe and an oozing infected blister!

One more arithmetic operation - because SPL is riddled with them. We can translate this to 2*(1-2*2*(-1)).

Length 73 snippet

You are nothing! Remember me. Recall your unhappy story! Speak your mind!

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

Length 74 snippet

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

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

Length 75 snippet

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

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

Length 76 snippet

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

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

Length 77 snippet

[Exit Hamlet]

[Enter Romeo]

Juliet:
 Open your heart.

[Exit Juliet]

[Enter Hamlet]

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

Length 78 snippet

The Ghost:
 Speak thy mind.

Lady Macbeth:
 Listen to thy heart! Remember thyself.

So, The Ghost (Hamlet's deceased father) is telling Lady Macbeth to output her value, while she orders The Ghost to read a number and push it into his stack.

  • 32
    This incredibly interesting and your profile picture is a perfect fit, he looks precisely like what I imagine an SPL programmer would look like. – overactor Jan 22 '15 at 9:34
  • 3
    @overactor I don't know whether to be insulted or proud to be likened to a Gumby. ^_^ – Rodolfo Dias Jan 22 '15 at 9:59
  • 9
    Bizarrely this is NOT the most obscure to read example here... and seems to be tied for "least practical". – H.R.Rambler Jan 23 '15 at 16:46
  • 6
    ROFL here's +1 to help you on the way - Once more unto the breach Rodolfo! – H.R.Rambler Jan 24 '15 at 14:31
  • 3
    @RodolfoDias You can begin. I'm waiting to see them. You have 120 up-votes. – ghosts_in_the_code Nov 13 '15 at 15:52

Piet

Factoid

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

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

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

1 Codel

1 Codel

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

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

2 Codels

2 Codels

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

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

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

3 Codels

3 Codels

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

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

4 Codels

4 Codels

Prints out 2 to stdout indefinitely.

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

5 Codels

5 Codels

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

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

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

6 Codels

6 Codels

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

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

7 Codels

7 Codels

Yet another echo program with a different look.

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

8 Codels

8 Codels

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

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

9 Codels

9 Codels

Adds 1 + 2 = 3, and then terminates.

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


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

12 Codels

12 Codels

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

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

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

15 Codels

15 Codels

Reads a number from stdin and outputs its' square.

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

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

20 Codels

20 Codels

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

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

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

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

25 Codels

25 Codels

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

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

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

30 Codels

30 Codels

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

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

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

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

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

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

The yellow pattern in the middle is never used.

54 Codels

54 Codels

Prints "hi!" to stdout

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

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

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

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

  • 5
    Hah yes, was waiting for this :) – Sp3000 Jan 20 '15 at 3:09
  • How's that any different from a 2D character language? It's just the way you convey the cell values. – JDługosz Jan 20 '15 at 3:31
  • 24
    @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. – Spencer Jan 20 '15 at 4:00
  • 13
    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... – trichoplax Jan 20 '15 at 5:37
  • 3
    The 9 codel example looks like a mini-pokeball. Nice. – The_Basset_Hound Aug 24 '15 at 1:23

><> (Fish)

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

Factoid:

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

Length 1 snippet:

X

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

Length 2 snippet:

1n

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

Length 3 snippet:

"o;

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

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

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

Length 4 snippet:

42n;

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

Length 5 snippet:

<v
;>

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

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

  • Program flow is initially rightward
  • < makes program flow leftward — we go off the left and wrap around to the v
  • v makes program flow downward — we go down to the >
  • > makes program flow rightward — we go off the right and wrap around to the ;
  • Finally, we terminate.

Length 6 snippet:

";"00p

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

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

Length 7 snippet:

\7*n;
6

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

  • Start rightward, but the \ reflects us downward
  • Push a 6 and wrap
  • Hit the backside of the \ and reflect back to rightward
  • Push a 7
  • Multiply the top two of the stack
  • Output and terminate

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

Length 8 snippet:

"r00g>o<

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

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

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

Length 9 snippet:

x0\>
\1n>

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

Length 10 snippet:

;a comment

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

Length 11 snippet:

1!X2!X+!Xn;

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

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

Length 12 snippet:

01v
ao>:@+:n

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

  • a: Push 10, which we need for newline. a-f push 10 to 15 respectively.
  • :: Duplicate top of stack
  • @: Rotate the top three elements of the stack, e.g. [5 4 3 2 1] -> [5 4 1 3 2].

Trace for the first few iterations:

enter image description here

Length 13 snippet:

i:d=?v
l?!;o>

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

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

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

  • l pushes the length of the stack
  • We check the length with ?:
    • If the length was nonzero, then the next instruction ! is executed, skipping the ;
    • If the length was zero, then we don't execute ! and terminate due to the ;

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

Length 14 snippet:

32.

   X67*n;

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

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

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

Length 15 snippet:

01+:aa*=?;:nao!

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

Length 16 snippet:

"r00g!;oooooooo|

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

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

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

'r3d*!;oooooooo|

Length 17 snippet:

b2,63,.

   17,n;

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

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

Length 18 snippet:

123456${{$}nnnnnn;

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

  • $: Swap the top two elements
  • {: Shift the whole stack left
  • }: Shift the whole stack right

To show how this works, here's the program trace:

123456 ------> 123465 ------> 234651 ------> 346512 ------> 346521 ------> 134652
       $ Swap        { L shift      { L shift       $ Swap        } R shift

Then we output, giving 256431.

Length 19 snippet:

"reward"4[roooo]oo;

Up until now I've been saying "the stack", "the stack"...

Although most programs use only one stack, ><> can actually have multiple stacks! Here are the relevant instructions:

  • [: Pops x and moves the top x elements to a new stack
  • ]: Removes the current stack, and moves its values to the underlying stack.

Here's the trace for the above program:

       [r e w a r d]       Push "reward"
4[     [r e] [w a r d]     Move four elements to a new stack
r      [r e] [d r a w]     Reverse the current stack
oooo   [r e] []            Output "ward"
]      [r e]               Remove the current stack, no values to move
oo     []                  Output "er", giving "warder" altogether

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

Length 20 snippet:

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

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

The above code is functionally the same as

aa*5+7a*2+oo;

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

Length 22 snippet:

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

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

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

enter image description here

Length 24 snippet:

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

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

Length 25 snippet:

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

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

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

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

Length 33 snippet:

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

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

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

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

enter image description here

Length 44 snippet:

a&>i:0(?v"+"$\
/&^?=0l< "a*"/
\:1+&2p/\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!

Once again, the input is expected to be digits only. Trace GIF here.

Length 74 snippet:

>i:'A'(?v:'N'(?v:'['(?v\
  :'a'(?v:'n'(?v:'{'(?v\
^      o<    +d<  -d-d<o

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

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

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

  • An idea for the 13 snippet: i:d=?v NEWLINE o;!?l< -- prints input line backwards – tomsmeding Jan 19 '15 at 17:29
  • 12
    I wish I could give this more up votes, I am now inspired to begin learning ><>... – Robobenklein Jan 20 '15 at 15:19
  • 6
    +1 for starting at top and going down (and also just because it's fun to read). – mbomb007 Jan 20 '15 at 19:01
  • 5
    @mbomb007 it's a shame, though, that the order can't go left/right and wrap to the bottom of the page :P – krs013 Jan 30 '15 at 5:14
  • Your length 8 snippet would be a true quine if you wrote something smells fishy... on the next line. – wizzwizz4 Jan 17 '16 at 16:30

C – edit

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

So why feature C?

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

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

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

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

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

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

Factoid

C rocks.

Length 0 snippet

World's shortest self-reproducing program http://www.ioccc.org/1994/smr.hint

Length 1 snippet

;

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

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

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

Length 2 snippet

x;

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

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

Length 3 snippet

??/

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

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

Length 4 snippet

f();

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

Note the fundamental differences between this and f;.

Length 5 snippet

s="";

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

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

Length 6 snippet

o=042;

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

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

Length 7 snippet

f(){f;}

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

Length 8 snippet

main(){}

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

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

Length 9 snippet

#define Z

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

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

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

Length 10 snippet

enum{P,Q};

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

Length 11 snippet

volatile v;

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

Length 12 snippet

#pragma once

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

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

Length 13 snippet

w(){for(;;);}

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

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

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

Length 14 snippet

int a[]={1,2};

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

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

Length 15 snippet

const long k=7;

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

Length 16 snippet

extern void **q;

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

Length 17 snippet

double d=4/3-1/3;

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

Length 18 snippet

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

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

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

Length 19 snippet

#include <stdlib.h>

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

Length 20 snippet

char*p=(char*)0x300;

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

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

Length 21 snippet

int w=sizeof(double);

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

Length 22 snippet

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

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

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

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

Length 23 snippet

union u{char c;int i;};

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

Length 24 snippet

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

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

Length 25 snippet

int main(void){return 1;}

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

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

Length 26 snippet

typedef struct{int x,y;}P;

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

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

Length 27 snippet

#define C(x,y)(((x)+1)*(y))

C has a convenient macro #define syntax.

A common newbie error is to omit inner and/or outer brackets, resulting in hard-to-find operator precedence errors.

Length 28 snippet

struct f{int s:1,e:8,m:23;};

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

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

Length 36 snippet

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

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

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

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

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

Length 48 snippet

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

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

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

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

Length 51 snippet

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

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

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

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

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

Length 63 snippet

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

Or formatted more sanely:

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

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

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

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

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

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

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

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

static int q = w;
static int w;

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

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

static int w;
static int q = w;

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

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

Length 74 snippet

void f(register int*p,register int*q,register int l){while(l--)*p++=*q++;}

Or laid out nicely:

void f(register int *p, register int *q, register int l)
{
    while (l--)
        *p++ = *q++;
}

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

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

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

Length 88 snippet

#include<stdio.h>
int f(int x){return(x>1)?x*f(x-1):1;}int main(){printf("%d\n",f(12));}

Or with a saner layout:

#include <stdio.h>

int f(int x)
{
    return (x > 1)? x * f(x - 1): 1;
}

int main()
{
    printf("%d\n", f(12));
}

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

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

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

f(12)

Becomes:

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

Without any function calls required!

Other compilers can reorganize the function:

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

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

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

Length 117 snippet

#include<stdio.h>
int main(int c,char**v){int a,b;sscanf(v[1],"%d%*[\t ,]%d",&a,&b);printf("%d\t%d\n",a,b);return 0;}

Or:

#include <stdio.h>

int main(int c, char **v)
{
    int a, b;

    sscanf(v[1], "%d%*[\t ,]%d", &a, &b);
    printf("%d\t%d\n", a, b);

    return 0;
}

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

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

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

Length 132 snippet

#include<stdio.h>
int main(int c,char**v){while(--c){++v;printf("|%s|\n|%5s|\n|%-5s|\n|%.5s|\n|%5.5s|\n",*v,*v,*v,*v,*v);}return 0;}

Or:

#include <stdio.h>

int main(int c, char **v)
{
    while (--c)
    {
        ++v;
        printf("|%s|\n|%5s|\n|%-5s|\n|%.5s|\n|%5.5s|\n", *v, *v, *v, *v, *v);
    }

    return 0;
}

The functions printf, sprintf, fprintf etc. use format specifiers to define the width and padding of the output.

Compile and run the above using command line arguments to see the various outputs:

> main xyz 123456
|xyz|                                                                                                                                                
|  xyz|                                                                                                                                              
|xyz  |                                                                                                                                              
|xyz|                                                                                                                                                
|  xyz|                                                                                                                                 
|123456|                                                                                                                                             
|123456|                                                                                                                                             
|123456|                                                                                                                                             
|12345|                                                                                                                                              
|12345| 

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

  • 4
    I don't think that there was a requirement to add a new factoid for each upvote :) – Optimizer Jan 19 '15 at 17:58
  • 26
    A common culture in C is to ignore compilation warnings, I don't think this is anywhere near the truth! – Shahbaz Jan 19 '15 at 18:57
  • 4
    If you have a large project and consider multiple compilers, it can be quite futile to try to eliminate all warnings. – feersum Jan 19 '15 at 20:06
  • 5
    This is excellent – Kik Jan 27 '15 at 21:05
  • 3
    I'm a C programmer, and I'm not scared of Haskell. – Shahbaz Mar 28 '16 at 21:58

x86 Machine Code

Factoid:

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

Length 1:

Now for the first program:

0xC3

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

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

Length 2:

Our next program:

0x4D 0x5A

or 'MZ' in ASCII.

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

DEC     BP
POP     DX

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

Length 3:

Now for an infinite loop:

41 E2 FD

Which translates to

start:
inc cx
loop start 

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

Length 4:

A program that is minimally useful:

40 CD 10 C3

Translated to assembly:

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

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

Length 5:

We can now implement a pause program:

B4 01 CD 21 C3

Translated to assembly:

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

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

Length 9:

Now to actually display output:

68 00 B7 07 AB 40 79 FC C3

Translated to assembly:

; These two instructions set up ES, the 'extra segment'
push 0xb700 ; 3 bytes
pop  es     ; 1 byte
label:
stosw       ; 1 byte, Store Word - Copy AX to [ES:DI] then add 2 to DI
inc  ax     ; 1 byte
jns  label  ; 2 bytes, Jump Not Signed - Jump unless the sign flag is set (when inc AX yields 0x8000
ret         ; 1 byte

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

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

Length 20:

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

B0 13 CD 10 68 0F A0 1F AC 31 C2 88 94 3E 01 87 D3 93 EB F4

In assembly:

mov al,13h      ; 2b
int 10h         ; 2b - Set the video mode to 13h

push    0xA00F  ; 3b
pop     ds      ; 1b - Set the data segment to video memory

start:          ; This loop runs 'Rule 90' to draw Sierpinski triangles
lodsb           ; 1b - load al with [ds:si] then increment si

xor     dx,ax   ; 2b - xor the left and right values of the previous row of pixels
mov     [si+318],dl ;4b - store result to memory

xchg    dx,bx   ; 2b - swap register values
xchg    ax,bx   ; 1b - swapping with ax is 1 byte shorter

jmp     start   ; 2b - infinite loop

Sample output: Sierpinski Triangles

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

Length 21

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

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

Translated to assembly:

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

Sample output:

c:\misc>cpuid.com
GenuineIntel

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

Length 26

We can now do interesting animations

B0 13 CD 10 C4 07 BB 40 01 59 99 89 F8 F7 F3 31 D0 AA E2 F6 26 FE 05 47 EB FA

In Assembly

mov al,13h     ;2b
int 10h        ;2b Enter Video Mode 13h

les ax,[bx]    ;2b Set ES to (roughtly) video memory
mov     bx,320 ;3b Set up  BX asdivisor
pop     cx     ;1b Zeroize CX

start:
cwd            ;1b Sign extend AX to DX, AX will never have the sign bit set so this zeroizes DX in 1 byte
mov     ax,di  ;2b Copy video memory pointer
div     bx     ;2b Divide by width to get AX = Y pos, DX = X pos
xor     ax,dx  ;2b X pos ^ Y pos
stosb          ;1b Store and increment video pointer
loop    start  ;2b CX starts at 0, so this will loop until it wraps around

cycle:
inc     byte [es:di];3b Increment value in video memory to animate
inc     di     ;1b Increment video memory pointer
jmp     cycle  ;2b Infinite loop 

And the output will look like this:

Marching XOR

The function X pos ^ Y pos produces an interesting fractal, especially when animated

Length 27

Not only can you generate text and graphics in a small x86 .com program, you can also generate sound and music:

BA 31 03 B0 3F EE BA 30 03 B0 93 EE B4 01 CD 21 3C 1B EE 3C 1B B0 7F EE 75 EC C3

In assembly:

    mov dx,0x331            ; value for the midi control port
    mov al,0x3F             ; command value to set midi mode to UART
    out dx,al               ; output the command to the midi control port
play_loop:
    mov dx,0x330            ; value for the midi data port
    mov al,0x93             ; midi instrument value (piano)
    out dx,al               ; output to midi data port
    mov ah,1
    int 0x21                ; read character from stdin, with echo
    cmp al,27               ; test if it is escape
    out dx,al               ; output the ascii value as the midi note to play
    mov al,0x7F             ; note duration
    out dx,al               ; output note duration
    jne play_loop           ; loop if escape was not pressed
    ret  

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

Length 29

Let's use an iterated function system to generate a Dragon Curve fractal:

B0 13 CD 10 89 D0 01 CA 29 C1 D1 FA D1 F9 73 03 83 E9 7A B4 01 CD 16 B8 02 0C 74 E6 C3

Translated to assembly:

mov  al,13h
start:
int  0x10    ; This does double duty, setting the video mode to 13h at program start,
             ; and calling the 'draw pixel at coordinates' interrupt when looping
mov  ax,dx   ; The next couple instructions are our IFS, the algorithm is aproximately
add  dx,cx   ; f(y) = 0.5x + 0.5y
sub  cx,ax   ; f(x) = 0.5x - 0.5y OR f(x) = 0.5x - 0.5y - 1
sar  dx,1    ;
sar  cx,1    ;
jnc  skip    ; This jump handles pseudo-randomly switching between the two functions for x,
             ; based on if the previous value of x was odd or not.
sub  cx,122  ; Magic number, chosen since it provides sufficent 'randomness' for a filled in
             ; fractal and a good scale to the fractal. 102 and 130 also work.
skip:
mov  ah,1
int  0x16    ; Get keyboard state, zero flag will be set if no key has been pressed
mov  ax,0xC02; Set up AH for the draw pixel function when int 0x10 is executed,
             ; AL = color, CX = column, DX = row
jz   start   ; Loop if a key hasn't been pressed
ret  

Output:

Dragon Curve

Pressing a non-control key will cause the program to exit. This is based off of Fire Coral by Desire on Pouet.net.

Length 52

This program is a bit of a double feature, it shows a bit of the x87 floating-point co-processor, and self-modifying code.

B3 07 D9 E8 B1 11 DE 0E 32 01 E2 FA BE 0A 24 56 B1 09 DF 34 AC D4 10 
86 E0 05 30 30 50 E2 F5 44 B4 2E 50 89 E2 B4 09 CD 21 FE 06 03 01 4B
75 D2 CD 20 0A 00

When run, the program will output several mathematical constants:

1.00000000000000000
3.32192809488736235
1.44269504088896341
3.14159265358979324
0.30102999566398120
0.69314718055994531
0.00000000000000000

These are One, Log2(10), Log2(e), Pi, Log10(2), Log e(2), and Zero.

In assembly:

org 100h

mov     bl,7         ;Counter for the total number of constants to print
start:
fld1                 ;Floating point constant to load on the FP stack,
                     ;start with 1 since it's op-code is the lowest

mov     cl,17        ;Multiply the constant by 10, 17 times to get the
mult:                ;printing part as an integer
fimul   word[ten]
loop    mult

mov     si,10+'$'*256;ASCII new line (10) and the end-of-string ($)
                     ;characters. These are used both as
push    si           ;a constant memory location, and stored to the
                     ;stack to format and printing

mov     cl,9         ;print 18 digits (9 pairs)
fbstp   [si]         ;store the integer part of the floating point
                     ;number on top of the FP stack as a packed
                     ;binary-coded decimal number (1 digit/nibble),
                     ;and then pop the number off the FP stack

convert:
lodsb                ;load a pair of packed digits

db 0xd4,16 ; AAM 16  ;ASCII Adjust For Multiply instruction using
                     ;non-standard base 16. This puts AL/16 in AH,
                     ;and AL%16 in AL, unpacking the digit pair.

xchg    ah,al        ;Swap the digit order
add     ax,'00'      ;Convert the digits to ASCII values
push    ax           ;Store digits on the stack
loop    convert

inc     sp           ;AX now holds the 1st 2 digits to print,
mov     ah,'.'       ;so to insert a decimal point, the 2nd digit
push    ax           ;is replaced with a '.', the stack pointer
                     ;is adjusted to overwrite 1 byte, and then
                     ;AX is pushed on the stack

mov     dx,sp        ;Load DX with the start of the print string
mov     ah,9         ;Load AH with the 'Print String' constant
int     21h          ;Call the 'Print String' interrupt to display
                     ;the constant

inc     byte[start+1];Self-modifying code - increment the load
                     ;floating point constant op-code to iterate
                     ;through all of them

dec     bx
jnz     start        ;Exit when all 7 constants have been printed
int     20h


ten: dw  10

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

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

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

Length 64

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

B0 13 CD 10 C4 07 99 89 F8 B9 40 01 F7 F1 83 E8 64 FE CE 31 DB 31 F6 
89 F5 0F AF F3 01 F6 0F AF DB 70 19 0F AF ED 70 14 01 EB 70 10 29 EB
29 EB C1 FB 06 01 D3 C1 FE 06 01 C6 E2 DB 91 AA EB C6

In assembly:

mov al,13h ; set up graphics mode 13
int 10h

les ax,[bx]; trick to set video memory

FillLoop:
cwd
mov ax,di  ; di is the current position on screen
mov cx,320 ; convert di int x,y screen coordinates
div cx     ; CX is the iteration counter, exit the loop if it hits
           ; zero before the value escapes.
sub ax,100 ; center the fractal vertically
dec dh     ; center the fractal horizontally

xor bx,bx
xor si,si

MandelLoop: ; Fairly standard Mandelbrot routine,
mov bp,si   ; exits if the values overflow
imul si,bx
add si,si
imul bx,bx
jo MandelBreak
imul bp,bp
jo MandelBreak
add bx,bp
jo MandelBreak
sub bx,bp
sub bx,bp

sar bx,6   ; We use fixed point math with the lowest 6
add bx,dx  ; bits being the fractional portion, so this
sar si,6   ; rescales the values after multiplication
add si,ax

loop MandelLoop

MandelBreak:
xchg ax,cx ; Write the escape itteraction as the color
stosb
jmp FillLoop

The end result is this image:

Mandelbrot Fractal

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

  • 5
    Of all of the languages to see on PPCG, I did not expect this. – Alex A. Jan 27 '15 at 0:58
  • 21
    Wow. Plus other characters to make this a comment. But seriously. Wow. – krs013 Jan 27 '15 at 8:29
  • 2
    @Michael Edenfield That's what DOSBox is for! – Sir_Lagsalot Jan 29 '15 at 20:22
  • 1
    20 byte Sierpinski is very impressive. – qwr Apr 8 '16 at 21:48
  • 1
    I consider myself to be a good programmer, but when I look at this I must admit defeat. – Stephan Bijzitter Sep 29 '16 at 21:51

Haskell

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

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

Length 86 snippet

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

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

sum (N (s 3) 7 (N E 5 (s 8))     === 23
product (N (s 3) 7 (N E 5 (s 8)) === 840
toList (N (s 3) 7 (N E 5 (s 8))  === [3,7,5,8]

and so on.

Here's a picture of our tree:

7
| \
3  5
    \
     8

Length 70 snippet

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

This is a prime sieve!

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

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

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

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

Length 68 snippet

Finally, a quine!

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

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

In Haskell, putStr is a function that just prints the contents of the string it gets to stdout; print, though, prints things to stdout. So, print 4 is equivalent to putStr "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 f fix recalls fix f, which recalls fix f, generating endless copies of the same computation. This version fixes it by defining r (result) to be the result; as such, f r = r. So, let's define r = f r. Now we return r.

Length 17 snippet:

f n=product[1..n]

This is the functional way to define factorial.

Length 16 snippet:

f n=(\x->x+x+x)n

(\x -> x + x + x) is a lambda (someone thought \ resembles the letter.).

(\x -> x + x + x) n is the lambda applied to n (this is exactly the same as n + n + n).

f is the multiply-by-three function (also f = (*3))

Length 15 snippet:

sum=foldl (+) 0

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

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

Length 14 snippet:

fix f=f(fix f)

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

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

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

Length 13 snippet:

f=sum.map(^2)

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

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

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

Length 10 snippet:

data B=T|F

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

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

Length 9 snippet:

main=main

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

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

Length 8 snippet:

f(x:_)=x

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

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

The patterns in this snippet are:

  • _: the pattern which matches anything and binds no variable.
  • x: the pattern which bind anything and binds it to the variable x.
  • :: this pattern gets to child patterns, that is, one for the head, and one for the tail. If the list is non empty, it matches them with the head and the tail.

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

Length 5 snippet:

x=2:x

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

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

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

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

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

Length 4 snippet:

2:[]

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

Length 3 snippet:

f.g

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

Length 2 snippet:

1-

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

Length 1 snippet:

1

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

factoid:

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

  • 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? – proud haskeller Jan 19 '15 at 13:49
  • Show it off in a snippet and add it in the explanation. – Martin Ender Jan 19 '15 at 14:12
  • f=0:1:zipWith(+)f(tail f) -- 25 chars, a functions that returns a lazy-calculated list of the Fibonacci numbers. – chamini2 Jan 20 '15 at 3:06
  • ugh i added a bunch of snippets and then my computer shut down – proud haskeller Jan 20 '15 at 18:42
  • @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. – mbomb007 Jan 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.

  • 1
    Lets see what you will be able to do with these characters... ;-) – proud haskeller Jan 20 '15 at 16:19
  • 9
    I would say that it's closer to java than C, actually – proud haskeller Jan 20 '15 at 16:20
  • Noted. I think we almost have enough to do some Linq - coming tonight! – BMac Jan 20 '15 at 21:36
  • public static implicit operator int(MyClass o){return o.objVal;} //65. With this code, this line is valid: MyClass o1 = new MyClass(10); int o2 = o1; // o2 is 10 now. msdn.microsoft.com/en-us/library/85w54y0a.aspx – Zukki Jul 21 '15 at 13:48
  • More snippets please – Cyoce Oct 2 '16 at 5:53

Java


Length 44 snippet

Object a=System.out.append("Hello, World!");

Prints Hello, World! to STDOUT.

Length 43 snippet

float[][][][][]a=new float[5][3][7][2][10];

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

Length 42 snippet

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

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

Length 36 snippet

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

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

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

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

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

Length 35 snippet

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

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

Length 34 snippet

public static void main(String[]a)

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

Length 33 snippet

enum D {NORTH, EAST, SOUTH, WEST}

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

Length 32 snippet

Files.readAllBytes("hello.txt");

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

Length 31 snippet

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

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

Length 30 snippet

new JFrame().setVisible(true);

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

Length 29 snippet

throws ClassNotFoundException

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

Length 28 snippet

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

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

Length 27 snippet

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

Creates a new array of strings.

Length 26 snippet

Object.class.newInstance()

Creates a new Object.

Length 25 snippet

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

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

Length 24 snippet

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

The successor function.

Length 23 snippet

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

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

Length 22 snippet

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

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

Length 21 snippet

Arrays.asList(2L,"a")

Creates an ArrayList with these elements.

Length 20 snippet

System.out.print(s);

Prints s.

Length 19 snippet

import java.util.*;

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

Length 18 snippet

Math.addExact(x,y)

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

Length 17 snippet

Double.MIN_NORMAL

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

Length 16 snippet

System.in.read()

Reads a single character from the console.

Length 15 snippet

Long.reverse(x)

Reverses the bits in the binary representation of x.

Length 14 snippet

int x=050+120;

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

Length 13 snippet

private C(){}

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

Length 12 snippet

static class

Allows the creation of inner classes without an enclosing outer class - a solution to a problem faced by many programmers.

Length 11 snippet

throw null;

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

Length 10 snippet

int[]a,b[]

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

Length 9 snippet

switch(x)

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

Length 8 snippet

break a;

Breaks out of the block labeled a.

Length 7 snippet

goto x;

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

Length 6 snippet

\u003b

Ends a statement. Java is weird.

Length 5 snippet

a-=-a

Doubles a by subtracting its negation.

Length 4 snippet

a&=b

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

Length 3 snippet

...

Any number of arguments, consolidated into an array.

Length 2 snippet

<>

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

Length 1 snippet

@

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

Factoid

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

  • 5
    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 – Optimizer Jan 19 '15 at 17:48
  • 4
    You just got down-voted, I guess this means you'll have to remove a snippet! ;) (The downvote was for "Java is weird") – Simon Forsberg Jan 19 '15 at 20:56
  • 1
    It seems that the snippet #36 is recursive and can be extended indefinitely: class A{class B extends A{B.B.B.B.B.B.B b;}} still compiles. – Natix Jan 28 '15 at 13:18
  • 3
    Upvoted to help you make a complete program ;) – durron597 Jan 28 '15 at 19:32
  • 1
    But it Java, [goto] triggers a mysterious RuntimeException Wrong. goto doesn't even compile. – dorukayhan Jun 25 '16 at 2:35

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.

Length 29:

import math
math.factorial(7)

Finds the factorial of 7, returning 5040.

Length 25:

import math
print math.pi

Python's math module provides many useful functions and constants. Here's PI. Returns 3.14159265359. (In the code above, I counted the newline as a character.)

Length 24:

f=lambda y:lambda x:x**y

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

Length 19:

print"Hello World!"

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

Length 16:

[x*3 for x in l]

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

Length 15:

import this #:)

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

Length 14:

lambda x:x**.5

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

Length 13:

1 if x else 0

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

Length 12:

s=input(">")

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

Length 11:

eval("2e3")

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

Length 10:

range(013)

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

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

Length 9:

a,b = b,a

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

Length 8:

#comment

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

Length 7:

l[::-1]

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

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

Length 6:

l[-6:]

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

Length 5:

1<x<5

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

Length 4:

0256

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

Length 3:

`3`

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

Works in Python 2 only!

Length 2:

[]

An empty list.

Length 1:

_

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

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

  • Beautiful is better than ugly
  • Explicit is better than implicit
  • Simple is better than complex
  • Complex is better than complicated
  • Readability counts

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

  • Anytime! I'm not gonna add anymore snippets (couldn't resist the Length 9 one!), since you're doing a great job with it already. Good luck! – nasser-sh Jan 22 '15 at 14:39
  • 1
    length 6: it would return [5, 6, 7, 8, 9, 10] (the last 6 numbers in the list) – Vincent Jan 23 '15 at 13:18
  • Length 16: l does not have to be a list, it can be any iterable object; tuples, lists and generators for example all work – nasser-sh Jan 23 '15 at 17:16
  • @Sp3000: I've used it with [restricted-source] challenges. – Robbie Wxyz Feb 2 '15 at 18:54
  • 4
    No love for the good old import antigravity? – Cipher Oct 22 '15 at 15:00

JavaScript

This goes newest to oldest. Link for myself: [edit]

Length 51 snippet:

console.log(require('fs').readFileSync(__filename))

A Node.JS quine this time, though it would fail any "strict quine" requirements, due to reading its own source code.

Length 50 snippet:

a=new XMLHttpRequest;a.open('GET','file');a.send()

Finally! An AJAX request (using Vanilla.JS). We initialize, open, and send the request, but I ran out of room to add handlers and actually do anything with the result.

Length 49 snippet:

msg=new SpeechSynthesisUtterance('Hello World!');

Prepare a vocal "Hello World!". It'll be a little more work to actually speak it. We can also adjust the volume, pitch, rate, and accent. See Speech Synthesis API on HTML5Rocks. Not yet supported by Firefox, certainly not IE.

Length 48 snippet:

function repeat(){setTimeout(repeat,48)}repeat()

Simulate setInterval by recursively setTimeouting.

Length 47 snippet:

module.exports=function MyModule(a) {this.a=a};

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

Length 46 snippet:

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

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

Length 45 snippet:

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

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

Length 44 snippet:

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

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

Length 43 snippet:

sq=[1,2,3,4,5].map(function(n){return n*n})

Creates an array of the first 5 squares, using map().

Length 42 snippet:

six="1+5",nine="8+1";eval(six+' * '+nine);

This works on the same principle as this, but JS lacks #define and so ends up uglier. It returns, of course, the answer to life, the universe, and everything.

Length 41 snippet:

c=function(){var i;return function(){}}()

The beginning of a closure. c is now a function (the internal one) with access to the internal variable i, but it doesn't do anything.

Length 40 snippet:

$('p').click(function(){$(this).hide()})

We are totally dropping those paragraphs and using jQuery.

Length 39 snippet:

script=document.createElement('script')

This is the beginning of adding a new external script. Create an empty <script> element, and keep a reference to it.

Length 38 snippet:

document.getElementsByClassName('abc')

Find all the the .abc elements in the document. Of course, with jQuery, it's only $('.abc')...

Length 37 snippet:

b=JSON.parse(JSON.stringify(a={3:7}))

Creates two identical, but decoupled objects, a, and b. If you would do

a={a:1};
b=a;
b.a=3;

you'd end up with a=={a:3}, because a and b point to the same object. We use JSON to decouple them.

Length 36 snippet:

(function f(){return "("+f+")()"})()

A quine. It prints its own source code.

Length 35 snippet:

document.body.style.display="none";

See #32. This one just hides the document, without overwriting the contents.

Length 34 snippet:

Object.prototype.toString.call(34)

Calling Object.prototype.toString is a good way to tell the type of an object. While 34..toString() is "34", the snippet is [object Number].

Length 33 snippet: (credit for this one goes to an anonymous user)

+0%-0.&(v\u0061r=~void[{}<<!(0)])

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

Length 32 snippet:

document.body.innerHTML="hacked"

Halp! Hazxxors!eleven!!11!

Length 31 snippet:

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

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

Length 30 snippet:

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

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

Length 29 snippet:

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

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

Length 28 snippet:

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

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

Length 27 snippet:

document.querySelector('a')

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

Length 26 snippet:

JSON.stringify({twenty:6})

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

Length 25 snippet:

new Badge("Good Answer");

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

Length 24 snippet:

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

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

Length 23 snippet:

window.parent==self.top

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

Length 22 snippet:

for(i in self)alert(i)

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

Length 21 snippet:

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

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

Length 20 snippet:

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

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

Length 19 snippet:

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

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

Length 18 snippet:

location.href="/";

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

Length 17 snippet:

(function(){})()

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

Length 16 snippet:

obj={not:'json'}

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

Length 15 snippet:

open('//s.tk/')

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

Length 14 snippet:

function f(){}

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

Length 13 snippet:

Math.random()

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

Length 12 snippet:

new Date<=12

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

Length 11 snippet:

Math.PI*121

The area of a circle with radius 11.

Length 10 snippet:

if('j')9+1

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

Length 9 snippet:

[9].pop()

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

Length 8 snippet:

document

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

Length 7 snippet:

alert()

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

Length 6 snippet:

var x=6

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

Length 5 snippet:

[][5]

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

Length 4 snippet:

+"4"

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

Length 3 snippet:

x=3

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

Length 2 snippet:

{}

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

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

Length 1 snippet:

1

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

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

  • 1
    Snippet 33 doesn't work on Firefox. Is it really valid JS? – Oriol Jan 24 '15 at 1:25
  • I find stringifying and reparsing an object to copy it so dirty. ECMAScript 6 introduces Object.assign, so snippet 37 becomes b = Object.assign({ }, a = {3 : 7}). – Oriol Jan 25 '15 at 10:37
  • @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? ;) – Scimonster Jan 25 '15 at 12:22
  • About #38, there's always document.querySelectorAll("element#id.classname[attribute]:not(somethingwedontwant)"). (Supports any valid CSS selector). – Mateon1 Jan 26 '15 at 16:46
  • The #40 snippet itself isn't so interesting, but the comment is priceless. – Scimonster Jan 27 '15 at 8:45

R

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

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


Length 32:

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

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

swiss[3, 2, drop = FALSE]

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

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

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

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

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

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

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


Length 31:

print(fortune("hadleywickham"))

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

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

Length 30:

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

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

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

enter image description here


Length 29:

summary(lm(mag~depth,quakes))

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

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

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

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

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

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

> summary(lm(mag~depth,quakes))

Call:
lm(formula = mag ~ depth, data = quakes)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.72012 -0.29642 -0.03694  0.19818  1.70014 

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.755e+00  2.179e-02 218.168  < 2e-16 ***
depth       -4.310e-04  5.756e-05  -7.488 1.54e-13 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3921 on 998 degrees of freedom
Multiple R-squared:  0.05319,   Adjusted R-squared:  0.05225 
F-statistic: 56.07 on 1 and 998 DF,  p-value: 1.535e-13

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


Length 28:

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

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

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

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

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


Length 27:

install.packages("ggplot2")

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

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

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


Length 26:

filled.contour(t(volcano))

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

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

enter image description here


Length 25:

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

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

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


Length 24:

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

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

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

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

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


Length 23:

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

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

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

enter image description here


Length 22:

unique(presidential$n)

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

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

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

Submitting this has an interesting result:

[1] "Eisenhower"  "Kennedy"  "Johson"   "Nixon"  "Ford"  "Carter"
[7] "Reagan"      "Bush"     "Clinton"

Notice how Lyndon B. Johnson's name is spelled... Oops.

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


Length 21:

integrate(dexp,0,Inf)

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

1 with absolute error < 5.7e-05

Length 20:

deriv(~cos(x^3),"x")

R can do symbolic derivatives! This returns:

expression({
    .expr1 <- x^3
    .value <- cos(.expr1)
    .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
    .grad[, "x"] <- -(sin(.expr1) * (3 * x^2))
    attr(.value, "gradient") <- .grad
    .value
})

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

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


Length 19:

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

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

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

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

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


Length 18:

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

A lesson in machine precision. This returns FALSE.


Length 17:

example(readline)

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

> example(readline)

readln> fun <- function() {
readln+   ANSWER <- readline("Are you a satisfied R user? ")
readln+   ## a better version would check the answer less cursorily, and
readln+   ## perhaps re-prompt
readln+   if (substr(ANSWER, 1, 1) == "n")
readln+     cat("This is impossible.  YOU LIED!\n")
readln+   else
readln+     cat("I knew it.\n")
readln+ }

readln> if(interactive()) fun()
Are you a satisfied R user?

Way to be modest, R.


Length 16:

acf(lh,t="part")

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

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

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

enter image description here


Length 15:

p3d(bunny,p=99)

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

enter image description here


Length 14:

stats:::rgamma

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

function (n, shape, rate = 1, scale = 1/rate)
{
    if (!missing(rate) && !missing(scale)) {
        if (abs(rate * scale - 1) < 1e-15)
            warning("specify 'rate' or 'scale' but not both")
        else stop("specify 'rate' or 'scale' but not both")
    }
    .External(C_rgamma, n, shape, scale)
}
<bytecode: 0x00000000098cd168>
<environment: namespace:stats>

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


Length 13:

sample(9,s=4)

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


Length 12:

LETTERS[-pi]

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


Length 11:

plot(bunny)

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

enter image description here


Length 10:

????sample

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

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

Alas.


Length 9:

isTRUE(1)

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


Length 8:

is.na(8)

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


Length 7:

stop(7)

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


Length 6:

x < -1

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


Length 5:

x<<-1

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


Length 4:

x<-1

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


Length 3:

!0i

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


Length 2:

NA

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


Length 1:

T

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

  • Yay R "!"(T) ! – Vlo Jan 20 '15 at 21:18
  • @Vlo: "!"(T) evaluates to FALSE. However, the statement "Yay R" is never false. ;) – Alex A. Jan 20 '15 at 21:34
  • 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")) – Vlo Jan 23 '15 at 20:31
  • @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. :) – Alex A. Jan 23 '15 at 21:05
  • 2
    @Jemus42 Ah, looks like you need to do data(bunny) first. – Alex A. Feb 18 '16 at 3:53

Brainfuck

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

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

0 0 0 0 0 0
    ^

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

Brainfuck has eight instructions:

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

Brainfuck to C:

#include <stdlib.h>

int main(void) {
    unsigned char* mem = calloc(30000, sizeof(unsigned char));
    unsigned int ptr = 0;

    // Put your brainfuck code here, converted to the matching expressions under "C equivalent"

    return 0;
}

Length 1 Snippet

Read one character and put it in the current cell.

,

Memory (with input: abc)

0 0 97 0 0 0
    ^

Length 2 Snippet

Add one to the current cell, and shift the pointer to the right.

+>

Memory

0 0 1 0 0 0
      ^

Length 3 Snippet

Remove one from the current cell until it is zero; Set the current cell to zero

[-]

Possible memory:

Memory: (Before)

0 0 100 0 0 0
    ^

Memory: (After)

0 0 0 0 0 0
    ^

Length 4 Snippet

Comments: In brainfuck, everything not a instruction is ignored. For that reason the following program is a totally valid (but empty) brainfuck program:

Hey!

Length 5 Snippet

A simple cat program (Write input to output)

,[.,]

Thanks to tomsmede for his comment

Length 6 Snippet

Move the value of the current cell to the cell to the right (Assuming the cell to the right is 0, otherwise it would add the value of the current cell to the value of cell to the right):

[>+<-]

In general, people use this code for moving a variable though.

Memory: (Before)

10 0 100 0 0 0
     ^

Memory: (After)

10 0 0 100 0 0
     ^

Length 25 Snippet

Reverse a six character input and print it, followed by every ASCII character (N-1)..1 (where N is the value of the first input character).

,>,>,>,>,>,.<.<.<.<.<[.-]

Length 53 Snippet

main(){i=0;j=0;if(i>=0){if(j<=i)i+=1;i-=1;}return 0;}

This minified C program is also a Brainfuck program in disguise, and vice versa! In fact, they (almost) do the same thing. Here's the Brainfuck code without the "comments" (C code).

><+-

Let me explain the Brainfuck code (and C code). As you can see, it uses two cells (i and j). It increments the first cell (increment i by 1). Then it decrements the same cell (decrement i by 1).

This is just a silly example of some source code being able to be compiled as two different languages and run (practically) the same.

  • 2
    ,[.,] -- 5 characters, cat program – tomsmeding Jan 19 '15 at 17:32
  • 12
    This may be the best "Brainfuck 101" I've ever seen. – hoosierEE Jan 22 '15 at 15:10
  • length 6: that would put the sum in the right cell, and zero the left one. Not move, right? – Filip Haglund Feb 15 '15 at 13:03
  • Added a dummy variable to length 6 to better explain the concept. The program will in fact add cell #3 to cell #4 and make cell #3 0. – YoYoYonnY Feb 17 '15 at 6:56
  • 58 votes -- could you update? :) – Conor O'Brien Apr 28 '16 at 2:10

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(); }

  • 2
    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. – Joe Z. Jan 24 '15 at 5:57
  • 1
    [](){} 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 – stefan Jan 28 '15 at 12:01
  • @stefan: indeed, I always forget it since it doesn't look function like then ;) I added it to the answer. – PlasmaHH Jan 28 '15 at 13:11
  • @PlasmaHH I absolutely hate it because indeed it doesn't look like a function.. ;-) – stefan Jan 28 '15 at 14:20

Regex

Length 2 snippet

[]

JavaScript: An empty character class that doesn't match anything.

PCRE, Java, Python re, Ruby (tested on version 2.0): Syntax error.

Length 1 snippet

.

., called dot-all, is available in all flavors I had a chance to look at.

What does it match?

I̧n͟ g̨͜e҉̡͞n̵͢e͜͝r̷͝a͘l̢҉,̡͟ ̴̕̕.̸̴̢̛́ ̸̡̢m͞ąt̴̨c͞h̛e͢͡s̶͘ ͘a҉n̛͜͠ỳ̸ ͢c̵̡hár͘͝a̕͢ćt͘͠e͏̀͠r̷̀ ̴̕͢ex͝͞͞c҉ep̀t̛ ̕f̴҉o͟͜r̴͢ ͞n͏ę͟w̢̕͜ ͡l͝i̸̧n͢͡e̶.͟

Java Pattern: In default mode, dot-all matches any code point, except for these 5 code points \r\n\u0085\u2028\u2029. With UNIX_LINES mode on (but without DOTALL), dot-all matches any code point, except for \n. With DOTALL mode on, dot-all matches any code point. From Java 5, Pattern operates on code point, so astral characters are matched by dot-all.

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

.NET: Same as Python. The dot-all mode in .NET is called Singleline.

JavaScript (C++11 <regex>): In default mode, dot-all matches any UTF-16 code unit, except for these 4 code points \n\r\u2028\u2029. With s flag on, dot-all matches any UTF-16 code unit. JavaScript also operates on UTF-16 code units.

PCRE: Depending on build option, dot-all can exclude \r, \n or \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.

Ruby (tested on version 2.0.0): In default mode, . matches any code point except for \n. Dot-all mode is accessible via m flag (!).

s flag is used to indicate Windows-31J encoding in Ruby.


Factoid

Ŗ͞e̡͟҉ǵ͟͢e̴̢͘͡x̡́͞ ̛̀҉҉̢c҉̷̨a̸̛͞n҉̛͠ ̷̸̀p̴͠͡҉̵ą̧͜͢r̸̸̷̢͝s̢̀͡e̷̷̷͘͞ ̨̧̀H̨̧͜͜T̷͞M̷̛͜L͢.̴̡́ Repeat after me. R̶̶̢̧̰̞̲̻̮̳̦̥ͭͯ́̓̎͂̈ͯͤ̇͊͊͟ĕ̱̹̩̪͈͈͍̗͎̝͚̽̈́ͨ̐̽ͪͮ̍͂͐ͮͧ̔̏̓ͣ̀ĝ̵̢̢̖̤̜̭͔͊͒ͦ͛ͤ͗ͬͧͪ̾͘͟eͦ̄ͭ̑̾҉̨̨̝̬̹̘̭͔͟͢x̣̻͓̠͈͕̥̜͚̱̝̫͚̳̾̍ͦ̑̈́̋̌̉̎͊ͮ͗̄̆̒́̚̚ͅ ̸̦͈̥̬̺͇͂ͧͧ̃͐̎ͮ̌ͤ̈́̒̆ͣ̈́̏̔͊̐̀ç̨̬̪̳̦͎̖͕̦͔ͨ̃̿̓̈́ͅȁ̸̳̺̠̭ͮ̎̓̐͘̕͜͡ņ̨̫͔͍̬̤̘͎͚̣̟̦͍̜ͭͭ̈́ͦ̈́̽͗ͥ̑͝͡ ̸̛̖̝̻̻͎̍̄ͭ̓ͨ̋͋̈́͗̌̇ͤ͋ͬ͘pͪ̒̍ͫͤͭ͊ͮ̇̿̆̐̄̎͌̚͏̧͏͇̼͚̰͓̲͕̰̖̘̟̞̺̲ḁ̛͇̫̻̉̊ͣͭͤ̇ͨ́͘͠rͦ̂̈́̆͑͊ͣ̊ͮ̉̉͆ͧ̒͛̐̋̚͏̴̭̫̞̯̘̖͍̼̖̜̞̖̩͕̹̻̮̗͜͡͞ͅs̟͈̺͖̦̟̙̦͖̤ͬ̋͌̄͂ͩ̓̐̔̓͌̾̀̈͊̊ͤ̀̚eͫ̐͒̽ͯͫͨ͏̨̡̦̤̙͍̙̪̝̮̤͎̭̖̪̻͙͍͖͉̀́ ͉̭̫̰͔̝͓̼̮͚̻͎͎͉̐͗͗͊̇ͣ͒͗͑̆͐̎̐̀ͬ͛ͮ͝H̢̥͕̼͓̫͙̺̼̮ͣͦ̍ͨ͒̔̌T̪̲̦̻̦͖̞̤͒̑ͭ̐̑̃ͭͣ͐̎̒̉͊̀͜͜M̞̪͇͕̩͉͗ͧ̌ͯ͋͂̉̍ͭ̓̇̐̌͜͠Ĺ̷̨̳̘̯͚͓͛͌ͭ̉̍.ͯ͆̊̌ͯ̇̓̏͐ͪ̋̈́͑̕҉̷̠̰̼̤̲̀́

  • 35
    I feel bad for anyone who doesn't get the factoid's reference. – Robobenklein Jan 20 '15 at 14:53
  • 5
    @robobenklein I know a secret medicine for your pain: Just enlighten us! – flawr Jan 20 '15 at 15:59
  • 23
    @flawr For those that don't know the famous question: the first answer at stackoverflow.com/questions/1732348/… is what you're looking for. – Robobenklein Jan 20 '15 at 16:07
  • 1
    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. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ Jan 20 '15 at 17:08
  • 12
    @n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, aren't you going to use all those votes to show us how to parse HTML? – mbomb007 Jan 23 '15 at 15:49

J

PS: Snippets now linked to tryJ.tk letting you play around with them running in JavaScript in your browser, without installing J.

PPS: I swapped order; this makes more sense for people joining in, and for future reference.

PPS: I think, due to time constraints, I will add one snippet a day

factoid:

J is a descendant of APL (see here for the family history) minus the funny character set.

Length 1 snippet

_

J uses _ both as infinity and as negative indicator, when attached to number literals (opposed to the verb -).

Length 2 snippet

a.

a. is called Alphabet, containing all 1 byte characters. As such J does not contain functions like atoi, since they are simple look-ups in the alphabet: a. i. 'z' =122

Length 3 snippet

i.9

i. is for Integers, when used monadically (ie. only one argument, the right one, usually called y). When used dyadically it serves as index of, as in the example above.

Length 4 snippet

!!6x

J supports arbitrary precision integer and rational numbers. This calculates the factorial of the factorial of 6 (a 1747 digit number).

Length 5 snippet

^.^:_ 

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

Length 6 snippet

^0j1p1

or equivalently

^o.0j1

Euler's Identity in J. As cited above, ^ is exp(). Apart from arbitrary precision integers and rationals, it also supports powers of pi and complex numbers, and combinations hereof as literals. 0j1p1 means (0 + j) * pi ^ 1.

Length 7 snippet

+/&.:*:

A verb taking the 2-norm of any vector. This demonstrates 2 things:

  • the Insert adverb turns the Add verb + into Sum by inserting it between each element of its argument. Hence (0+1+2+3) = +/ i.4 .

  • The conjunction Under when used as v &.: u y is equivalent to vi u v y, where vi is the obverse (generally the inverse).

Yes, J knows about functional inverses. Combining these makes the verb in the snippet equivalent to %: @: (+/) @: *:, or sqrt(sum(y.^2)) in Matlab for instance.

Length 8 snippet

$#:I.@:,

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

 ($#:I.@:,) 5 = i. 5 5 NB. indices of 5 in i. 5 5

Length 9 snippet

<"1 i.4 6 

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

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

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

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

Length 10 snippet

<./ .+~^:_

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

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

^:_ iterates this step till convergence.

Example, displaying original and shortest path distances:

(]; <./ .+~^:_ ) wtm=: _6]\0 2 5 _ _ _ _ 0 4 1 3 _ _ _ 0 _ _2 _ _ _ 4 0 _ 5 _ _ _ _1 0 6 _ _ _ _ _ 0

Length 11 snippet

<.@o.10x^99

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

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

Length 12 snippet

($-.1:)($,)]

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

Length 13 snippet

1 :'-u%u d.1'

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

For example:

(_2 + *:) (1 :'-u%u d. 1')^:_ ] 1 NB. root of x^2-1; ] is there to avoid combining _ and 1 into an array.

Length 14 snippet

(%-.-*:)t.i.10

First 10 numbers of the Fibonacci series by Taylor expansion of x / (1 - x - x^2). Analyzing the hook %-.-*: gives (y % (-.-*:) y) = (y % ( (1 - y) - *: y).

Length 15 snippet

(#{.+//.)!/~i.9

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

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

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

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

Length 16 snippet

;/@~.,. <"0@#/.~:

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

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

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

Note that because the prevasive concept of Rank, this code works for any dimensionality.

Length 17 snippet

*./ @:(#&>)@C.@A.

J supports a few primitives specifically about permutations:

  • Anagram A. Monadically it finds the Anagram index, dyadically, it applies the permutation specified by the anagram index in the left argument to the right argument.
  • Cycle - Permute C. converts between direct and cycle representation of permutations.

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

]n=: (p=:?!9) *./ @:(#&>)@C.@A. i.9 NB. period of a random permutation
p&A.^:n i.9 NB. applies permutation n times.

Length 21

<:@(#/.~)@(i.@#@[,I.)

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

It exploits Interval Index I. for finding the interval of:

If y has the shape of an item of x , then x I. y is the least non-negative j such that j{x follows y in the ordering, or #x if y follows {:x in the ordering or if x has no items.

Making the totals of each interval is done using key as highlighted in snippet 16.

The snippet linked to on tryj.tk demonstrates the central limit theorem using this histogram:

(bins=:(%~>:@i.)10) ( [ (graph=:(,&":"0 1 '#'#"0 1~])) (histogram=:<:@(#/.~)@(i.@#@[,I.)) ) (+/%#) ?5 200 $ 0

Length 22

=,&(+/)(~:#[)e.&~.~:#]

Fun in J. This implements a mastermind engine, taking a secret array as left argument, and a guess as the right. The values returned are the number of white and black pegs. Taken apart:

NB.   ExactMatch: checks where digits correspond:
ExactMatch =: =

NB.   GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right
NB.   pairs of parentheses, and checks them for same elements(e.), after eliminating
NB.   doubles in both (&~.)
GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ])

NB.   Piecing the conditions together, after summing the booleans:
mm =: ExactMatch ,&(+/) GoodDigitWrongPlace

To be used like

secret (=,&(+/)(~:#[)e.&~.~:#]) guess

Where secret and guess are any array. It works with any data type actually.

  • 16
    Well, either you get an unreadable heap of weird symbols, or you get an unreadable heap of ASCII symbols. Pick your poison. – John Dvorak Jan 19 '15 at 12:57
  • 16
    @JanDvorak All languages are unreadable until you learn them. ;-) – Gareth Jan 19 '15 at 13:10
  • 5
    I used to think long, descriptive names aid code comprehension. Then I was enlightened. – hoosierEE Jan 22 '15 at 15:09
  • @Gareth But not all are unreadable even after you learned them. Not gonna name any names. – flawr Apr 13 '15 at 20:27

RPL (Redstone Programming Language) [and Minecraft]

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

Factoid:

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

Length 1:

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

Length 2:

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

enter image description here

Length 3:

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

Length 4

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

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

Length 5

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

enter image description here

Length 6

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

enter image description here

  • 6
    You haz 13 upvotes, I can haz 10 moar programs? – Riker Mar 31 '16 at 15:33
  • 4
    None of your programs are actually written in RPL, so don't pass it off as such. This is purely Minecraft "code". – mbomb007 Apr 20 '16 at 16:06
  • 2
    You have a deficit of 14 programs m8. I'd like to see what you have in mind ;) – Conor O'Brien Apr 21 '16 at 18:02
  • 4
    You haz 21 upvotes, I can haz 15 moar programs? – wizzwizz4 Apr 30 '16 at 18:28
  • 1
    You haz 29 upvotes, I can haz 23 moar programs? – bb010g Aug 9 '16 at 19:56

TI-BASIC

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

Length 31 snippet

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

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

Menu("CHOOSE VALUE","AREA",A,"CIRCUMFERENCE",C
Lbl A
Disp πR²
Stop
Lbl C
2πR

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

Length 29 snippet

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

Real (on by default) places the calculator in real number mode, so calculations involving complex numbers throw a NONREAL ANS error. When put in a+bi mode, the calculator displays answers as complex numbers if applicable, so the second example returns 4i. re^θi mode uses polar instead of rectangular coordinates, so it outputs 4e^(1.570796327i).

Length 23 snippet

If A≥9
Then
1→X
7→Y
End

This is just a simple conditional, although there can be an Else statement. Then and End are not required if it is just one statement.

Length 21 snippet

(-B+√(B²-4AC))/(2A)→X

Everyone's favorite, the quadratic formula. Stores the first solution to a quadratic equation as X, assuming a, b, and c are stored in their respective variables, as in ax2 + bx + c.

Length 20 snippet

Shade(|X/2|-3,5-X²,0

This shades the intersection of the two functions, with several optional parameters: minimum and maximum values of x and direction of and distance between the shading lines.

Length 18 snippet

LinReg(ax+b) L1,L2

Here we calculate the linear regression equation, or the linear equation that best matches a group of points, with the x-values stored as a list in L1 and the y-values in L2. There are many other regression options available, including quadratic, cubic, and exponential.

Length 17 snippet

dbd(1.2711,1.2115

This calculates the number of days between two dates, in this case January 27, 2011, the day this site started, and January 21, 2015, the day this was written. (That's 1455 days for the lazy.) The way to encode dates is a little strange: either DDMM.YY or MM.DDYY, leading zeroes optional.

Length 16 snippet

For(A,0,5
Disp A

This shows two parts of the programming side of the language. The first is your typical for loop, similar to for(var A=0;a<5;a++) in other languages. (You should also use the End command to break out of the loop.) The second is self-explanatory: it displays A, in this case 5 times because of the loop.

Length 15 snippet

Y1=|X³-4|
Y2=3X

Here are two examples of a well-known feature of graphing calculators: graphing equations. You can have 10 different equations graphed on the same plane, and there are many useful commands to find intersections, maxima, values of x, etc. Those equations look like this when graphed on a standard window:

Graph

Length 14 snippet

[[1,2][34,5]]T

The brackets are used to make matrices, and the T transposes the matrix:

[[1 34]
 [2 5]]

Length 13 snippet

dayOfWk(9,1,6

This finds the day of the week of January 6, 9 AD. The output is a number where 1 is Sunday, 2 is Monday, and so on. This particular date was a Tuesday, so the output is 3.

Length 12 snippet

Circle(1,3,5

The first of the basic drawing tools, this draws a circle on the graph with a center at (1,3) and a radius of 5.

Length 11 snippet

randInt(0,8

This generates a (pseudo-)random integer between 0 and 8 inclusive. There is an optional third argument that tells how many integers to generate. There are several other random functions, including ones for normal and binomial distributions, one for a random matrix, and one for a randomly ordered list with no repetitions. randInt can be seeded by storing a number as rand: 2→rand.

Length 10 snippet

4>5 or 2≠7

Here we have TI-BASIC's (in)equality and logic operators. The inequality statements evaluate first to 0 or 1, and or returns true if either side is true, so this displays 1.

Length 9 snippet

.656▶F◀▶D

This can convert from decimal to fraction and vice versa, which is very useful. There are also dedicated ▶Frac and ▶Dec functions that only go one way. Prints 82/125 in this case.

Length 8 snippet

lcm(14,6

This prints the least common multiple of 14 and 6, which is 42.

Length 7 snippet

getDate

Pretty self-explanatory, just prints the current system date as a list, in this case {2015 1 19}.

Length 6 snippet

√({4,9

Arrays (or lists) are surrounded by braces and separated by commas. This is similar to the map function of many languages, where it iterates through each element of the list and applies the operation outside the braces to it, in this case square root, so the result is {2 3}. Note that closing parentheses are optional, so they will be omitted from now on.

Length 5 snippet

4iii6

We've got a couple of cool things going on here. First, the real parts, 4 and 6 are multiplied, and then the imaginary parts are multiplied: i^3, or -i. These multiplied give -24i. This showcases funky-looking juxtaposition multiplication and TI-BASIC's handling of imaginary numbers.

Length 4 snippet

8°5′

This is 8 degrees, 5 arcminutes, which is converted to degrees as 8.0333...

Length 3 snippet

8→T

This shows how numbers can be stored as variables, which is somewhat unusual because the number goes first, followed by the store arrow, then the variable name. As mentioned in the factoid, θ (theta) can also be used as a variable, and variables can only be one uppercase letter.

Length 2 snippet

4M

Similarly to Mathematica, you can multiply with juxtaposition, no * necessary. All variables are initialized to 0 by default, so this will output 0 unless you have stored something else to that variable (see snippet 3).

Length 1 snippet

e

This is the constant for Euler's number, which displays as 2.718281828.

Factoid

Variables can only store certain datatypes. For example, AZ (and θ) store numerical values, str0str9 store strings, and [A][J] store matrices (2-dimensional arrays).

  • By the way, the lower case n (not n) can also be used as a variable. – Ypnypn Jan 21 '15 at 15:28
  • Interesting. I've never used that variable. – NinjaBearMonkey Jan 21 '15 at 16:40
  • 3
    One can argue about str0 being 1 character or being 4. All instructions in TI-BASIC are 1 character long. – Ismael Miguel Jan 23 '15 at 18:51
  • @IsmaelMiguel I thought about that, but they are 1 or 2 bytes, and I decided to count characters normally. – NinjaBearMonkey Jan 23 '15 at 19:27
  • 1
    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!) – Ismael Miguel Jan 23 '15 at 19:31

GNU Sed

I am self-imposing a more restrictive requirement - all snippets will be complete sed programs.

Factoid

sed is a turing-complete language. Here is a proof.

Length 0 Snippet

I don't think a length 0 snippet is strictly required, but since it actually does something in sed, here it is:

Sed is the "Stream EDitor", i.e. it reads the stream (line-by-line) from STDIN, edits, then outputs to STDOUT. The zero-length sed program simply copies STDIN to STDOUT. Thus the cat utility may be emulated by sed. The following are equivalent:

cat a.txt b.txt > c.txt

and

sed '' a.txt b.txt > c.txt

Length 1 Snippet

=

This sed program prints the line number of each line to STDOUT. This is approximately equivalent to:

nl

or

cat -n

although the sed version puts the line number on its own line.

Length 2 Snippet

5q

Copies STDIN to STOUT and quits after line 5. This is equivalent to:

head -n5

You might be starting to see a bit of a pattern here - sed can be used to emulate many of the standard core-utils tools.

Length 3 Snippet

iHi

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

  • 2
    See also USEFUL ONE-LINE SCRIPTS FOR SED, which is basically how I learned sed – Adam Katz Aug 27 '15 at 22:08
  • You have more votes. Can we have some more? – luser droog Jan 15 '16 at 3:37
  • 2
    Your factoid 404'ed. – Wauzl May 9 '16 at 7:36
  • 1
    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. :) – Wildcard Nov 10 '16 at 7:59
  • 1
    @Wildcard Yes - I've restricted this to GNU sed. – Digital Trauma Nov 14 '16 at 20:31

Python

(mbomb007's post already has a plethora of Python snippets, but I thought I'd chip in with some quirkier facts)

Factoid

Python is a dynamically typed language with an emphasis on readability.

Length 1 snippet

1

In Python 3, the above is equivalent to True in the sense that 1 == True (and also 0 == False). Note that this doesn't necessary hold true in Python 2, where you can redefine the value of True.

Length 2 snippet

<>

<> is an obsolete comparison operator equivalent to !=. It still works in Python 2 (although its use is discouraged), and was removed altogether from Python 3.

Length 3 snippet

...

Python has a number of features which no builtin uses, but is there solely for the sake of third-party libraries. This Ellipsis object is one of them, and it is typically used for slicing. For example, if we have the following 3D numpy array:

array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

then a[..., 0] (equivalent to a[:,:,0]) gives all the first elements:

array([[1, 4], [7, 10]])

In Python 3 the ... literal can be used outside of the slicing syntax, which amusingly allows you to use it as a "to-do" marker in place of pass or NotImplemented:

def f(x):
    ... # TODO

Length 4 snippet

(1,)

A one-element tuple in Python.

Python has lists (e.g. [1, 2, 3, 4]) which are mutable, and tuples (e.g. (1, 2, 3, 4)) which are immutable. One common use for tuples is as dictionary keys, since lists aren't hashable.

A common beginner mistake is to leave out the comma above, i.e. (1), which is just the number 1 surrounded by parentheses. The one-element tuple is the only time you need a comma before the closing parens — it raises a SyntaxError if you try to put one in the empty tuple (), and is optional for tuples of length at least 2.

Length 5 snippet

0or x

There's a few things going on in this snippet, so let's take a look!

or is like || in many languages. In Python, A or B short-circuits, returning A (without evaluating B) if A is truthy, otherwise it returns B. For example, 1 or x always returns 1, as 1 is always truthy, and even works if x is not defined. On the other hand, 0 or x either returns x if x is defined, or throws a NameError if it isn't.

When golfing, we can usually drop the whitespace between a number and an or, such as 1 or x becoming 1or x. This is possible because 1or starts with a digit, making it an illegal Python identifier.

However there is one exception — 0or, which mysteriously throws a SyntaxError. Why? Because octal literals in Python start with 0o (e.g. 0o20 == 16), and the parser chokes when it reaches the r!

Note: In Python 2, octal literals may also start with a leading zero, e.g. 020.

Length 6 snippet

*x,y=L

This snippet demonstrates a special type of assignment in Python, where L is a list, tuple or any other sort of iterable.

In Python, you can "unpack" tuples and lists like so:

a,b = [1,2]

This assigns 1 to a and 2 to b. This syntax is also used for multiple assignment, such as

a,b = b,a+b

which is useful when writing a program that computes the Fibonacci series.

If the lengths on both sides don't match, then a ValueError is thrown. However, Python 3 introduced a new syntax, extended iterable unpacking (or more colloquially, "starred assignment") which allows you to do things like this:

*x,y = [1, 2, 3, 4, 5]

This assigns y to the last element, 5, and x to the rest of the list, i.e. [1, 2, 3, 4]. You can even do something like this:

a,b,*c,d,e = [1, 2, 3, 4, 5, 6, 7]

which assigns 1 to a, 2 to b, [3, 4, 5] to c, 6 to d and 7 to e.

Length 7 snippet

zip(*x)

zip is a function which takes a bunch of lists and, well, zips them up:

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]

Note: In Python 3 a zip object is returned instead, so if you want a list like above you'll need to wrap the call in list()

It's quite a convenient function if you have two or more related lists, and you want to link up their respective entries.

Now say you want to unzip the list — how would you do so? We can try to use zip again, but unfortunately this gives:

>>> zip([(1, 4), (2, 5), (3, 6)])
[((1, 4),), ((2, 5),), ((3, 6),)]

The problem is that everything is in the one list, but zip takes the individual lists as separate function arguments. To fix this we introduce the * splat operator, which takes a list/tuple/etc. and unpacks them as function arguments:

f(*[1,2]) ==> f(1, 2)

And the result is:

>>> zip(*[(1, 4), (2, 5), (3, 6)])
[(1, 2, 3), (4, 5, 6)]

Length 8 snippet

x='a''b'

The first time I saw this, I was a little taken back — what does it mean to have two strings next to each other? The answer was simple:

>>> x
'ab'

Python merely concatenates the two strings! This is extremely useful for readability, since it allows you to break up long strings like so (note the surrounding parentheses):

x = ('This is a very long sentence, which would not look very nice '
     'if you tried to fit it all on a single line.')

Length 9 snippet

0!=2 is 2

You may already know that Python allows chaining of comparison operators, so 5 < x <= 7 is only true if 5 < x and x <= 7. If you didn't know that... then surprise!

Anyhow, lesser known is the fact that, since is/is not/in/not in are also comparison operators, they can be chained too. In other words, the above code is equivalent to (0 != 2) and (2 is 2), which is True.

Note: There are a few subtleties with the 2 is 2 half though, since is checks whether two things are the same object, not whether two things are the same value. Python caches small integers so 1+1 is 2 is True, but 999+1 is 1000 is False!

Length 10 snippet

x=[];x+=x,

What happens when you add a list to itself? If we try printing x, we get:

[[...]]

Fortunately, Python's print is intelligent enough to not explode trying to print recursive lists. We can then do a bunch of fun things, like:

>>> x[0][0][0][0][0]
[[...]]
>>> x[0] == x
True

This feature also works with dictionaries, and is one way of creating data structures with cycles, e.g. a graph.

Length 11 snippet

help(slice)

The help function is very useful for debugging in Python. When called with no arguments in REPL, help() starts a help session, in which you can look up documentation for functions/data types/etc. When called with a specific argument, help will give information on the related item.

For example, help(slice) gives the following information (truncated since it's quite long):

Help on class slice in module __builtin__:

class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 | ...

As for slice, as we can see we can create slice objects for indexing. For example:

>>> L = list(range(10))
>>> L[slice(2, 5)]         # L[2:5]
[2, 3, 4]
>>> L[slice(2, None)]      # L[2:]
[2, 3, 4, 5, 6, 7, 8, 9]

Another useful function for debugging is dir(), which returns all names in the current scope when called without an argument, and returns all attributes of a given object when called with an argument.

Length 12 snippet

round(5.0/2)

What does this evaluate to? The answer depends on your Python version!

In Python 2, division between two integers results in integer division (i.e. 5/2 == 2) whereas in Python 3 we get float division (i.e. 5/2 == 2.5). However, this is division between a float and an integer, which should always result in a float. Why would we get different results then?

If we take a look at the documentation for round for both Python versions, we'll find the answer:

  • In Python 2, round tiebreaks by rounding away from 0.
  • In Python 3, round tiebreaks by rounding towards the closest even integer.

In other words, 5.0/2 = 2.5 rounds to 3 in Python 2, but rounds to 2 in Python 3. Rounding towards the closest even integer might sound weird, but it's actually called banker's rounding, and tries to treat positive and negative values similarly to reduce bias.

Length 13 snippet

class C:__x=1

Being object-oriented, Python has classes. The above is a class C which has a single attribute __x set to 1.

We can access class attributes using dot notation. For example, if we have the class

class MyClass(): my_attr = 42

then printing MyClass.my_attr would result in 42, as expected.

However, if we do the same and try to access C.__x as defined above, we get:

AttributeError: type object 'C' has no attribute '__x'

What's going on? C clearly has an __x attribute!

The reason is that attributes starting with __ emulate "private" variables, something which Python does not have. Python mangles the name of any attribute starting with __, appending the class name so that name reuse conflicts are avoided. In the above example, if we were really determined to access that 1, we would instead have to do

>>> C._C__x
1

Length 14 snippet

NotImplemented

Not only does Python have classes, it also has operator overloading. For example, you can have a class

class Tiny():
    def __lt__(self, other):
        return True

where __lt__ is the less-than operator. Now if we make an instance of Tiny, we can do this

>>> t = Tiny()
>>> t < 1
True
>>> t < "abc"
True

since we've defined __lt__ to always return True. Note that we can also do

>>> 42 > t
True

but the following breaks:

>>> t > 42
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    t > 42
TypeError: unorderable types: Tiny() > int()

Wait, how does that work? We haven't specified a behaviour for greater-than with Tiny, so it's not surprising that the last case breaks. But then how does an int (42) know that it's greater than our Tiny object?

Python has a builtin constant NotImplemented, which can be returned by a comparison special method. Let's try it out:

class Unknown():
    def __gt__(self, other):
        # __gt__ for greater-than
        print("Called me first!")
        return NotImplemented

Now if we make an instance of our new class:

>>> u = Unknown()

We can do this:

>>> t < u
True
>>> u > t
Called me first!
True

As we can see, what happened for u > t is that Python tried to call the greater-than method for Unknown first, found that it was not implemented, and tried the less-than method for the other class (Tiny) instead!

Length 15 snippet

x=[],;x[0]+=[1]

This is a bit of a fun one. First we assign x to be [], which is an empty list inside a tuple, i.e. ([],). Then we do x[0]+=[1] which tries to extend the empty list inside by the second list [1].

Now, remember that lists are mutable and tuples are immutable – what happens when you try to change a mutable object inside an immutable object?

>>> x=[],;x[0]+=[1]
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    x=[],;x[0]+=[1]
TypeError: 'tuple' object does not support item assignment

Oh so it gives an error, I guess that's to be expected. But what if we try to print x?

>>> x
([1],)

Huh? The list changed!

If you're curious about what's happening here, be sure to check out this blog post.

Length 16 snippet

@lru_cache(None)

Just add cache! This is a simple example of a decorator available in Python 3.

Suppose we have the following naïve Fibonacci implementation:

def f(n):
    if n < 2: return 1
    return f(n-1) + f(n-2)

As most introduction to programming courses may tell you, this is a very bad way of implementing Fibonacci, leading to exponential runtime since we're effectively just adding a lot of 1s at the base case. f(10)? Runs in a split second. f(32)? Take a while, but it gets there. f(100)? Nope.

But if we cache the results, things should get a lot faster. We could always use a dictionary for the cache, but let's try something else instead:

from functools import lru_cache

@lru_cache(None)
def f(n):
    if n < 2: return 1
    return f(n-1) + f(n-2)

As we can see, all I've done is import lru_cache from the functools module and added @lru_cache(None) before my function. @ denotes a decorator which wraps around a function, in this case for memoisation. lru_cache's first argument is maxsize, the maximum size of the cache – here we've set it to None to indicate no maximum size.

Now if we try to use it:

>>> f(100)
573147844013817084101

And it didn't even take a second!

Note: f(1000) leads to a recursion depth error, but that's a story for another time

  • What range of small integers does Python "catch" for the is operator? – mbomb007 Apr 6 '15 at 16:37
  • @mbomb007 From this question, it appears to be -5 to 256. You can try -5-1 is -6 and 255+2 is 257 to test. – Sp3000 Apr 6 '15 at 16:40

Matlab

Snippet 26 - iterate over matrices

This is something I just recently discovered. Usually you iterate over a given vector in for loops. But instead of vectors, you can also use matrices (rand(10) produces a 10x10 matrix with uniformly distributed numbers between 0 and 1).

for k=rand(10);disp(k);end

This then displays one column vector of the random matrix per iteration.

Snippet 25 - easy plotting

We know plotting is easy in matlab, but there is a super easy function ezplot (E-Z get it? It took quite a while until I finally got it, as I spelled Z always as sed instead of c, whatever...) Everyone likes elliptic curves:

ezplot('y^2-x^3+9*x-10.3')

elliptic curve

Snippet 24 - integration

The old fashioned word (but still in use in numerical computation) for integration is 'quadrature', can you guess what the result of the following one is?

quad(@(x)4./(1+x.^2),0,1)

Snippet 23 - images

Of course Matlab is also very popular among scientists who have to work with images (e.g. medical image analysis), so here is a very handy function. First argument is the image, second the angle and the third optional argument here tells the function to crop it to original size.

imrotate(rand(99),9,'c')

here

Snippet 22 - music

load handel;sound(y,Fs)

It will sound about like this (youtube link)

Snippet 21 - differentiate & integrate

polyint(polyder(p),c)

You can easily differentiate and integrate polynomials by using those two functions. When integrating, you can pass a second argument that will be the constant.

Snippet 20 - back to polynomials

p=poly(r);cp=poly(A)

Want the polynomial with the roots in r? Easy: p=poly(r). Want the characteristic polynomial of a matrix A? Easy: cp=poly(A). So roots(p) is exactly r (or a permutation of r).

Snippet 19 - another magic trick

fminsearch(fun,x0);

There are people who absolutely love this function. This basically just searches a minimum of fun with an initial value x0 (can be a vector) without any conditions on fun. This is great for fitting small models where you cannot (or you are too lazy) to differentiate the error/penalty/objective function. It uses the Nelder-Mead simplex algorithm which is pretty fast for functions where you cannot make any assumptions.

Snippet 18 - intro to polynomials

p=polyfit(x,y,deg)

Matlab has a nice solution for coping with polynomials. With polyfit you get a least squares polynomial of degree deg that approximates the points in x,y. You get a vector p that stores the coefficients of the polynomials, because that is the only thing what you need for representing a polynomial. If you go back to snippet 15, you can do the same thing by writing c = polyfit(x,y,2). So e.g. [1,-2,3] represents the polynomial x^2 - 2*x+3. Of course there are also functions for fitting other elementary, or arbitrary functions.

Snippet 17 - angles and discontinuities

unwrap(angle(c))

If you want to get the argument of a 'continuous' vector of complex numbers you often get back values that seem to have a discontinuity. E.g. angle([-1-0.2i,-1-0.1i,-1,-1+0.1i,-1+0.2i]) will get you [-2.94,-3.04,3.14,3.04,2.94] since angle only returns angles between -pi and pi. The function unwrap will take care of this! If you get a discontinuity like this, it will just add a multiple of 2*pi in order to remove those: '[-2.94,-3.04,-3.14,-3.24,-3.34]' This even works for 2d-matrices! If you just plot the argument of complex numbers with a negative real part you get the first graphics you'll get the first image, with unwrap you get the second one:

without unwrap with unwrap

[x,y] = meshgrid(-1:0.01:0,-0.5:0.01:0.5);
z = x+i*y;
imagesc(angle(z))
imagesc(unwrap(angle(z)))

Snippet 16 - scalar product

[1;2;3]'*[4;5;6]

Of course there are built in methods (like dot), but with the matrix-transformation operator ' it is as simple as that. If you do not know whether you have row or column vectors, you can just use a(:)'*b(:) where a(:) always returns a column vector.

Snippet 15 - linear least squares, the ugly method with the magic wand

[x.^2,x,x.^0]\y

x is the (column) vector with the values on the x-axis, y the noisy y-values. Type c=[x.^2,x,x.^0]\y and you get the coefficients of the 2nd degree polynomial. Of course you can use one of the billion builtin fit functions of matlab (how boring) why not use the magic wand?=)

x = (-1:0.1:2)';
y = 3*x.^2-2*x+1+randn(size(x)); %add some gaussian (normal) noise
A = [x.^2,x,x.^0];
c = A\y              %output: c = ]3.0049; -2.3484; 1.1852]
plot(x,y,'x',x,A*c,'-')

linreg

Snippet 14 - graphs

gplot(graph,x)

That is how to plot a graph. graph should contain a square adjacency matrix and x should be a nx2 matrix that contains the coordinates of each node. Lets make a random graph: graph = triu( rand(8)>.7) (make a Matrix that contains 0s and 1s, get only the upper triangle for an interesting graph). x = rand(8,2) then plot with some fancy styles gplot(graph,x,'k-.d')

graph (I declare this as modern art.)

Snippet 13 - meshgrid

meshgrid(a,b)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depending on two variables, you can just define a vector of values for the x-axis and one for the y-axis (a and b). Then with meshgrid, you can create two matrices of the size len(a) x len(b) where one has only the vector a as column, and the other has only the column has only the vectors b as rows. Usage example:a = -3:0.2:3;[x,y]=meshgrid(a) (if both vectors are the same, it is sufficient to just pass one.) Then you can just type z=x.^2+-y.^2 and e.g. mesh(x,y,z). This works for an arbitrary number of dimensions! So this is not only great for plotting, but also for getting all possible combinations of different vectors etc... (So, if you want to create a new code golf language, this should be in there, just make sure you use a shorter function name...)

mesh

Snippet 12 - plotting

plot(x,x.^2)

Take a vector x=-3:0.5:3 and and let plot do the rest. There are many more functions for plotting this is just a very basic one that you can use all the time. It would be already enough to write plot(v) and the data in v will be plotted against the array indices. How simple is that? If you want to style your plot, just add a string as a third argument: e.g. 'r:o' will make a red, dotted line with circles around the data points. If you want multiple plots, just add more arguments, or use matrices instead of vectors. Foolproof. plot

Snippet 11 - function handles

f=@(x,y)x+y

This is an example of a function handle that gets stored in f. Now you can call f(1,2) and get 3. Function handles in matlab are very useful for math functions (e.g. plotting) and you can define them in one line. But one drawback is that you cannot have conditionals or piecewise (and therefore no recursion). If you want this, you have to use the function statement and declare a new function, and each of those has to be stored in a separate file... (WHYYYYYY????)

PS: You'll get another funny easter egg if you type why in the console: They made a huge function that produces random messages like:

The tall system manager obeyed some engineer.
The programmer suggested it.
It's your karma.
A tall and good and not excessively rich and bald and very smart and good tall and tall and terrified and rich and not very terrified and smart and tall and young hamster insisted on it.

...which is very comforting if you are desperate enough to ask the console why...

Snippet 10 - How does my matrix look?

spy(eye(9))

As you know by now eye(9) creates a 9x9 identity matrix. spy just creates a that shows the zero/nonzero entries of the matrix. But you can also use it for displaying any binary 2d data. If you call spy without argument you'll get a nice little easter egg=)

spy on identity spy easteregg

Snippet 9

kron(a,b)

The kron function evaluates the Kronecker product of two matrices. This is very useful for discretisized multidimensional linear operators. I also used it every now and then for code golfing. You want all possible products of the entries of a and b? kron(a,b), here you go.

Snippet 8

5*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.

  • 1
    I have this problem very often...setting i to something and then experiencing unexpected behavior when it is not the complex unit. – feersum Jan 19 '15 at 20:10
  • 3
    Nice easter egg! If you type 'edit spy' you find an example of code obfuscation :-) – Abulafia Jan 21 '15 at 12:11
  • 1
    I went to upvote this and then realized I already had. Alas, if only I could upvote it again. Keep 'em coming, @flawr! – Alex A. Jan 21 '15 at 15:30
  • 2
    If you are running out of inspiration on things to show, I can recommend the Mathworks blog: On the Art of MATLAB by Loren Vershure Often they describe best practices that can be shown within the character limit. For curiosities consider Abandon Matlab, and for undocumented functions and features you can go to Undocumented Matlab by Yair Altman – Dennis Jaheruddin Jan 23 '15 at 14:20
  • 1
    @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 :) – rayryeng Jul 22 '15 at 20:01

Jot

Factoid: I can define Jot with 2 upvotes, and prove that it's Turing complete with 8 (not using lengths 4, 6, or 7).

Length 1

1

This is an example of two functions in Jot. The first is the empty string, which evaluates to the identity function. The second is 1, which is Jot's grouping operator. 1 evaluates to λxy.[F](xy) (lambda calculus notation), where [F] is the program before the 1 (here, the empty string). So, this program is the function λxy.(λz.z)(xy) which simplifies to λxy.xy.

Length 2

10

Now we are introducing the other symbol in Jot: 0. Again if [F] represents the value of the program so far, 0 evaluates to [F]SK, where S and K are from combinatory logic. I've defined the entire language now.

Length 5

11100

I will now prove that Jot is Turing complete by defining a mapping from combinatory logic to Jot. This Jot program is the K combinator.

Length 8

11111000

This is the S combinator.

Length 3

1AB

Here, A and B are not part of Jot, but rather placeholders for an arbitrary expression. The expression AB in combinatory logic maps to 1AB in Jot, with A and B recursively transformed by these three rules. QED

Length N

1
10
11
100
101
110
[...]

Every natural number, expressed in binary, is a valid Jot program. Consequently, I can algorithmically generate more snippets of arbitrary length. Given enough upvotes, I can solve the halting problem.

  • 2
    Two upvotes given. Now define the language. – John Dvorak Jan 19 '15 at 14:20
  • @JanDvorak working on it...it's been so long since I researched this thing that I forgot all of it :) – Phil Frost Jan 19 '15 at 14:22
  • 1
    I don't see why this should continue getting more upvotes. You are simply going to generate random binary numbers of increasing length :| – Optimizer Jan 19 '15 at 15:18
  • 1
    You said so for upvote number 4. But here we are looking at a "random number you just generated" – Optimizer Jan 19 '15 at 15:21
  • 1
    how can you solve the halting problem? I'm guessing it has something to do with using an infinite (number of infinite) program? – Filip Haglund Feb 21 '15 at 12:29

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.

  • Actually, ] is not purely decorative. [ will refuse to function if its last argument isn't ]. – FUZxxl Jan 26 '15 at 21:36
  • 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. – Riot Jan 26 '15 at 21:39
  • 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. – FUZxxl Jan 26 '15 at 21:40
  • 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 :) – Riot Jan 27 '15 at 0:15
  • 1
    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;} – kojiro Jan 29 '15 at 2:02

APL

Factoid

APL (A Programming Language) started out as an interpreter for a formula notation devised by Ken Iverson. When the language was designed, people used teletypwriters to communicate with computers. The character set of these was limited, but due to their construction, one could put multiple characters into the same position to compose complex characters. This feature is heavily used by APL, contributing to its infamous reputation as a read-only language.

You can try out most of the examples on http://www.tryapl.org.

Length 1

The character , called lampshade, both for its shape and for the enlightment you get from its presence, introduces a comment. Historically, it was created by overstriking a (jot) and a (up shoe).

Length 2

⍳3

The monadic (one argument) function (iota) generates a vector of the first few natural numbers. For instance, the aforementioned ⍳3 would yield 1 2 3, the vector of the first three natural numbers. On some implementations of APL, it would yield 0 1 2 instead, this depends on the value of ⎕IO, the iota origin.

Length 3

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⍵}.

  • You've got more votes! Can we have some more? – luser droog Jan 14 '16 at 5:59
  • @luserdroog Sure, let me think of some more. – FUZxxl Jan 14 '16 at 9:16
  • May I edit and extend this? – Adám Jul 12 '16 at 5:33
  • @Adám Yes, please. – FUZxxl Jul 12 '16 at 14:19
  • ∘.×⍨a gives me a value error. Am I using it correctly? – Cyoce Sep 13 '16 at 21:55

CJam

Try the below snippets here

Length 20 snippet:

q~{]__~z\z<=\~*0>*}*

A min-mod calculator. An excerpt from the question :

The minmod function is a variant of the familiar min, which appears in slope-limiting high-resolution schemes for partial differential equations. Given a number of slopes, it picks out the flattest slope, while taking care of relative signs between the slopes.

The function takes an arbitrary number of parameters. Then minmod(x1, x2, ..., xn) is defined as:

  • min(x1, x2, ..., xn), if all xi are strictly positive
  • max(x1, x2, ..., xn), if all xi are strictly negative
  • 0, otherwise.

Length 18 snippet:

l'[,65>Dm>_el+_$er

A ROT13 encoder. Shifts only a-zA-Z characters from the input string via STDIN

Length 15 snippet:

T1{_2$+}ri2-*]p

A full program to print the first N numbers from a Fibonacci series where N is provided as an input via STDIN.

Length 12 snippet:

{{_@\%}h;}:G

A simple GCD function. This can be used like 2706 410 G to get the GCD on stack.

Length 11 snippet:

123456 789#

# is the power operator. This snippet shows a cool feature of CJam that it supports BigInts for almost all mathematical operations. So the output of the above code is

1596346205622537943703716803040694151242100030904924074732295184521676912291137885341977590649991707684635184329980991487148618486236239062505001539322685142817506810040361209550544146292158784625519911512640361780862459268161619223326802388689703997604303632605734938879647069477372395799326590488746599202521617640394227957532720581758771344616555153473551874187964029973716015080326283503474062024803237072761129557356772954771383125420283743787215768524095651476398918270831514362626616089349128838080859262141293069421199363839940462244772673481244848208112002212957221705577938865719802035511067875502253218277834350725436729497351901219311577128600087062378434520948898301738545267825952998284599001356281260973911216650526574435975050678439968995805415462116669892745933523276658479456263859786003695570642598885206779863730608803831608206418317758451327165760242416052588688579435998154295782751455020445483571514197850814391880423853968520336337963918534259580183058727377932419280412466915889059399591196961188841001024998633317094826403760131868252088477018937989608302521450181593409274231460335072324865982559395114735391976545471553525054490202974741119144469523879456646833238659929705233941114530149037245274032070536718197592615630616792756562341411027203615235147973615347081993563361626845258162606172599728677944001956482301240050182368840648532697569098833480384074404562991348377266778603059081932412368912313845464302833428950934701568958836851009236647605585910687215977468114323293396641238344799575626940766355697576957869656153567798618227770961980620119004224798449940378878601283741944503399682599666873704888519152796472231721010884561046439019823540214190109829183178504573391524533915085342799888899681052113605127068137552531204917650779012455136663716975904242872042805633443567570913936237754642040107392687168596924804730637819953463737212774674563401663682370631910559669378413063684132477269578881395521544729393136204246705936061735379354437327940116154383441927197123218522827575163913310005036963663583344508839784971260123709283218409462028161021477446586507813599051643059982983426688872855309396405653159417356549291603532443699350168178837164682957610433456205211423600319694496115159970718912091395232327389520091646132878609779171226748990343349416763319432268713023302555895744813731889452605219001900815755497209921418814092923394321459962373890912709775151652200071533644718727513889263907829300496554849544461628702471995210369421320165755673222520834013956492183306187393652197405863508709529644837118590847002900783148394313160749018413291215958936871830666201928218294362550829287373305552379418641499562597137520153409556227576809855521876196531587454478159211299517511047868125975115347272184123454929507976958328038242400918390689757262398695703472270927183494613959476164389143107240083171566284628032072645081703351075328092783401422849512230275075331561337345714881104575020436358133210849231625973013523497330004645467493618279226202227586584610761439335895760888873155403816627190368675397978355381544497413492223577022267403347927237298551052219150516984577176643706356698282552857754120841266435149587248192704898338826251727748499150285409036076919533685800933215325289882260771526293167171975367192287689881199864600661035143522211647660445960687046757311913589429739868592726372013684511683081229044622752191694278221303073075505531920922815724661725685493922212700535444400760813940151761980008355835574184921854364539924999643954874549857103642483664109073938527328920827803218865362851320233433429604394590974694396314165313743853607609394553133883545319222169958204731303672940856293527174545435349105954532301106962634516087237739490953930886293289854731305112253177512851251930821765454042415085420000484369355605183062368648992392499663861508991984554431113080399485470268940148600970493633737364443822752829774334511729579419931500217970224646496435527826186627011323464848141074486509849545954714213290443775688291020289759390171236344528896

Length 10 snippet:

"`%W_"_W%`

We've already done quine, lets reverse it!. This is one of the shortest reverse quine in CJam. Reverse quine is a quine which prints its sources code in reverse order.

Length 9 snippet:

5,K,+_&S*

This snippet showcases a lot of features of CJam,

5, "create an array of numbers 0 to 4"
K, "create an array of numbers 0 to 19"
+  "List concatination"
_  "Duplicate top stack element"
&  "Set distinct operator in this case"
S* "Join array elements with space character"

Length 8 snippet:

"`_~"`_~

One of the smallest possible quines in CJam. This is a true quine in a sense that it does not actually read the source code in any manner. (Reading the source code is not even possible in CJam)

Length 7 snippet:

"AB"_m*

m* creates all the Cartesian products of the top two stack elements. For instance, the above code will put ["AA" "AB" "BA" "BB"] on stack, which is the cartesian product of "AB" and "AB".

Length 6 snippet:

"_~"_~

A nice looking repeated code. DO NOT run this :) . This representation of code is the basis for the simplest quine in CJam. You put string "_~" on stack, make a copy (_) and evaluate it. Which in turns does the same thing again (and again ..) until you reach maximum recursion exception.

Length 5 snippet:

{A}:F

This is how a basic function works in CJam, The above expression assigns the code block {A} to variable F. Now in your code, you can put F anywhere to run the code block (and get 10 in this case)

Length 4 snippet:

"A"~

You can evaluate any code block or string or even a single character using ~. The above expression results to 10

Length 3 snippet:

Kmr

A typical random number generator from range 0 to K i.e. 20.

Length 2 snippet:

es

This gives the current timestamp (milliseconds from the epoch). CJam also has et for local time in a more usable format which returns an array comprising of the various parts of the current time ( day, hour etc).

Length 1 snippet:

A

CJam has almost all capital alphabets as predefined variables. A is 10, B is 11 and till K is 20. P is pi (3.141592653589793), N is new line and many others. These can come very handy when you need initial values in variables, or even when you need two digit number in 1 byte.

Factoid

CJam is inspired by GolfScript but builds a lot of features on top of it including support for a network GET call :D

PS: I will try to update the answer every 5 upvotes or every 2 hours (which ever is earlier)

  • There are some issues with your ROT13 example :p But I'm impressed with the quine, I think I'll borrow it :) – aditsu Feb 1 '15 at 17:44
  • @aditsu what is the issue ? – Optimizer Feb 1 '15 at 17:46
  • It changes the case of n-z letters. Also, it has an @ for no reason, you can put the D there instead. – aditsu Feb 1 '15 at 17:49
  • @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 – Optimizer Feb 1 '15 at 17:52
  • 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. – aditsu Feb 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#).

  • That last edit! Quick, someone make an Beatles-themed esolang:D – fede s. Mar 23 '16 at 23:53
  • 1
    @fedes. John McCarthy, Paul McCartney... the language shall be called CarthyCartney. – cat Apr 28 '16 at 2:40

GNU Make

I'll go out on a limb on this one. I think this may well be the first time that make has been featured in PPCG.

Factoid

Make may be considered to be a functional language.

Length 0 snippet

I don't think length 0 snippets are required, but here is one anyway. I think this might be the most useful of all length 0 programs. With an empty Makefile (or even no makefile at all), make still has a bunch of built-in rules. E.g. there are default built-in rules to compile a .c file into a .o or binary, given the .c file exists in the current directory. So if we do:

make hello.o

make will find the .c to .o rule and compile hello.c to give hello.o

Similarly if we do:

make goodbye

If there is a goodbye.c file in the current directory it will be compiled into the goodbye binary.

Length 1 Snippet

TAB

Yes, the TAB character. While this doesn't do much on its own, it has great significance in Make. Specifically all recipe lines following a target definition in a rule MUST start with a TAB. This causes all sorts of frustrations when debugging makefiles when TABs and spaces get mixed up.

Length 2 Snippet

$@

This is an automatic variable for use in recipes. It will expand to the filename of the target of the rule. There are other useful automatic variables.

Length 3 Snippet

a:=

Shortest simply expanded variable assignment. The variable a is set to "" immediately when the Makefile is first parsed. If instead we do a=, then the assignment is recursively expanded, i.e. expansion is deferred until the time the variable is actually referenced.

Length 4 Snippet

W:;w

Shortest marginally useful complete rule specification. This defines a target W with a rule that simply runs the w shell command. Thus

make W

is equivalent to:

w

This is an alternative rule syntax in that the recipe follows the target on the same line separated by a new line. More commonly the recipe lines immediately follow a separate target line, with TAB characters starting each recipe line.

Length 5 Snippet

$(@D)

Another automatic variable. Similar to $@, but this expands to the directory portion of path, with the filename and trailing / removed.

  • Maybe some string functions like $(basename ) or $(patsubst )? (eg.) – luser droog Sep 11 '16 at 6:36

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.

  • 2
    beat me to it. nice snippets! – Sparr Jan 19 '15 at 16:24
  • your length 12 snippet seems to take two inputs, and print out two different fibonacci numbers. was that intentional? – Sparr Jan 21 '15 at 17:50
  • @Sparr, yes it was to showcase how functions work in Marbelous a bit. – overactor Jan 21 '15 at 20:41
  • maybe add that to the explanation? from what you wrote, I'd expect the snippet to take one input and output one fib number. – Sparr Jan 21 '15 at 20:54
  • I really hope you get to 40 points so my fibonacci function will fit... – Sparr Jan 21 '15 at 20:55

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.

  • +1 for Forth. I was starting to look for languages that hadn't been done yet. Happy to see it here already. – mbomb007 Jan 20 '15 at 19:33
  • 2
    Also, if you ever get to +1675, I've got a nice ASCII image to output. :D – mbomb007 Jan 20 '15 at 19:39

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

  • Needs more votes to show the true characteristics of COBOL. – idrougge Mar 12 '17 at 3:22
  • "the next one would come in at 26 characters" and we have 30 votes. What now? – Jerry Jeremiah Feb 7 at 0:33

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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