Showcase of Languages

  • 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:"",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=""></script><base href=""><ul id="list"></ul>

  • 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][email protected]##3#2'@t^[email protected]@#@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:

    [email protected]{[email protected]{{0,0},p=θ~(h={[email protected]#@#2,[email protected]#@#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


    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:


    Length 69 snippet


    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


    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


    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


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

    [email protected]@{"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

    [email protected][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,[email protected]]

    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


    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


    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[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


    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

    [email protected]@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


    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

    [email protected]{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


    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


    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


    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:


    Length 21 snippet


    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


    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


    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


    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


    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


    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


    We would get


    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


    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


    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


    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


    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


    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


    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


    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


    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.


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

    Awesome though the Sunset function may be, the time it actually returns these days makes me very sad.

    RE 22 : Chemestrica

    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'sHobbies Just tried it... picked an unfortunate `z` offset... smacked me right in the face.

    Can you prettify the code? Probably with `` since Mathematica isn't supported except on

    @MartinButtner At least the functions would be a different color.

    @mbomb007 Just tested it, it looks fairly reasonable.

    I wonder how long would be a snippet that searches for a random snippet inside `Neat Examples` section from Wolfram Documentation :)

    I assume the next patch will have `MathematicaData["Examples",Length]`

    The official Mathematica website should absolutely link to this.

    How can you have an exact value for Pi?

    @durron597 By keeping it as a symbol and making all your trigonometric and complex functions aware of what to do with a π.

    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.

    `GeoGraphics[]` would be nice for the missing length 13 I think. Show a high quality map of your current location :D

    @Calle Heh, I actually considered that ... I might use it for something more advanced for a longer snippet. There's a deleted length-13 snippet in the revision history.

    Many long snippets are missing!

    @Caridorc Sorry, I've sunk a lot of time into this over the past week so I took a bit of a break. I think this answer still has more snippets than any other though. ;) And I'll probably add a couple more if I come up with nice ideas that are actually more interesting than what I already have.

    @Martin Butter Awesome,thank you for the dedication! :)

    Nicely done! Have you went through **TaP** ?

    @VitaliyKaurov Oh, I didn't know that. Thank you! I might have a look for something for 100 and ~120. I've got something up my sleeve for 150, but I can't seem to get an interesting version of it for any less than that.

    You may also look at NEW-IN-X stuff, other X - adjust URL accordingly - can find some wonderful stuff there.

    @VitaliyKaurov Found something on TaP which I wanted to look into anyway. I'll have a look around the new-in-x as well. Thanks again!

    Grats on achieving more +1's than the question itself!

    I believe `[email protected]@CurrentImage[]` is a 33 character live webcam edge detector

    @benwaffle Neat! That is actually really nifty, I'll probably include that later.

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


    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:


    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:


    Used in a comparative between two "characters".

    Length 3 snippet:


    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:


    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:


    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:


    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] 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:


    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.

    (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

    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

    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

    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

    Speak your mind.

    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.

    Speak your mind!


    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

    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

    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

    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

    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

    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

    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

    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

    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

    Am I better than you?

    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]

    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]

    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.

    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 I don't know whether to be insulted or proud to be likened to a Gumby. ^_^

    Which number system did you use for the calculation `2*2*(-1) = -6`?

    @Nobody A system only I know, apparently... (yes, it was an error, meanwhile corrected)

    Bizarrely this is NOT the most obscure to read example here... and seems to be tied for "least practical".

    @H.R.Rambler "Least practical", you say? Wait until I begin with arithmetic operations (if I get more 100 upvotes, of course)...

    ROFL here's +1 to help you on the way - Once more unto the breach Rodolfo!

    Wish I could upvote more than once... This is interesting stuff.

    @RodolfoDias You can begin. I'm waiting to see them. You have 120 up-votes.

    Only 6239986 votes to go for a quine.

    Can we have more snippets?

    Does SE seriously has support for SPL code highlighting? Does anyone use this programming language in reality? Or they did it for fun?

    "Not better" should be `<=`, not `<`.

    +1 for `my little pony`.

  • Piet


    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.

    Hah yes, was waiting for this :)

    How's that any different from a 2D character language? It's just the way you convey the cell values.

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

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

    Could you explain what each codel in each image does individually? This is harder to understand than ><>.

    @mbomb007 I've updated the descriptions on most of the programs to add more detail, hopefully it's clearer now.

    The 9 codel example looks like a mini-pokeball. Nice.

  • ><> (Fish)

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


    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 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:


    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:


    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:


    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:


    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:


    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:


    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:


    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:


    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:


    ! 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:


    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:


    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:



    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:


    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:


    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


    Length 17 snippet:



    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:


    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:


    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:

    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


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

    Length 22 snippet:

    1&fv ;n&<

    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:


    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:

    ^ ,2v?%2:/

    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:

    /&^?=0l< "a*"/

    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:

    ^ 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

    I wish I could give this more up votes, I am now inspired to begin learning ><>...

    +1 for starting at top and going down (and also just because it's fun to read).

    @mbomb007 it's a shame, though, that the order can't go left/right and wrap to the bottom of the page :P

    Your length 8 snippet would be a true quine if you wrote `something smells fishy...` on the next line.

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


    C rocks.

    Length 0 snippet

    World's shortest self-reproducing program

    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


    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


    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


    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


    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


    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


    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


    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


    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


    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


    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

    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;
    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

    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:



    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

    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;}


    #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

    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;}


    #include <stdio.h>

    int main(int c, char **v)
    while (--c)
    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|

    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.

    I don't think that there was a requirement to add a new factoid for each upvote :)

    @Optimizer - Until I can get into some actual compile-and-link code, I'll add an explanation for those more familiar with scripting languages.

    That can take a whiiile

    _A common culture in C is to ignore compilation warnings_, I don't think this is anywhere near the truth!

    If you have a large project and consider multiple compilers, it can be quite futile to try to eliminate all warnings.

    Wrt #7, gcc will not automatically return 0; usually you get some garbage value.

    "A common newbie error is to omit the second group of brackets, resulting in hard-to-find operator precedence errors." It might be worth noting that your example still does not have enough brackets. You've protected against things like 2*C(2,2) but not things like C(2+0,2).

    @user19057 - thanks for catching that, corrected.

    @feersum - after confirmation, #7 revised, thank you.

    suggestion: do something with the "complex" datatype

    Thank you. Just letting what I wrote pass public opinion before I continue. Also looking at the C99 exception handling which almost everyone ignores!

    For #8 : the shortest compilable and linkable program is actually `main;`, which however crashes at runtime.

    #18 puts is a macro defined in stdio.h fputs deosn't require a header.

    @Quentin - I wonder if you can set it to an op-code for RETN, e.g. main=195; for Intel x86, and have it return without error? It's still one character more than main(){}!

    @Jasen - I guess it depends on distribution. In `gcc`, no macros in ``. Too many problems with macros, in particular address of to use in callbacks.

    This is excellent

    As a developer who began with C myself (before moving to Python, and not counting Visual Basic), I can confirm that Haskell freaks me out.

    Can we talk about code snippet 0. Which points to a copyrighted quine that has no code it in. Does that mean they copyrighted null???

    @DisplayName101 - haha - he should be claiming payment on the infinite copies everyone has of this program!

    @Kik Am I the only one who thought of Mr Burns when I saw that comment?

    I'm a C programmer, and I'm not scared of Haskell.

    FYI: OOP has nothing to do with operator overloading, a language can be object oriented without it.

    So what about `volatile const`? I can guess a useful interpretation that it might have, but I don't know if it is correct.

    @ChristianSievers - Can be used for a read-only hardware register — `const` prevents writing to it, which in some cases might have unintended effects, while `volatile` ensures no optimizations are done with respect to accessing it.

  • x86 Machine Code


    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:


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

    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

    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
    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
    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:


    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

    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

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

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


    Dragon Curve

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

    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:


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

    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

    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

    xchg ax,cx ; Write the escape itteraction as the color
    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.

    Of all of the languages to see on PPCG, I did not expect this.

    Wow. Plus other characters to make this a comment. But seriously. Wow.

    this takes me back a ways! Too bad I can no longer hand-edit .com files in 64-bit Windows 8 :\

    @Michael Edenfield That's what DOSBox is for!

    20 byte Sierpinski is very impressive.

    I consider myself to be a good programmer, but when I look at this I must admit defeat.

    Wow, it is very interesting about `MZ`!

    Where can I learn it ?

    @VictorVosMottor Try the sizecoding wiki.

    Heh thx I'll check it out. Welcome back to SE (ig you were not on SE). XD

  • 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:

    | \
    3 5

    Length 70 snippet

    primes=sieve[2..] where

    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:


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


    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:


    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:


    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:


    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:


    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:


    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:


    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.


    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?

    Show it off in a snippet and add it in the explanation.

    `f=0:1:zipWith(+)f(tail f) -- 25 chars`, a functions that returns a lazy-calculated list of the Fibonacci numbers.

    ugh i added a bunch of snippets and then my computer shut down

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

    You should update this! More ideas: a typeclass `instance` for your tree type, polymorphic recursion, `Fix`, `filterM` powerset, primes, quine?

    @Lynn feel free to add some of your own, and edit the existing ones, I just don't have enough time.

    In the length 38 snippet, you say you define a `foldr`, but where is it defined?

    @BrianMcCutchon thanks for reading! yeah, sorry, for some reason the length 86 snipet is actually missing. you would've thought someone would have spotted that earlier... well, I'll try to look into it soon

    Since you asked ("am I clear?"): I couldn't figure out how 14 works - how is it interpreted and what's the execution order? Also, what does `x=infinite loop` mean (does the `fix` call lead to an infinite loop, or does it return an "infinite loop" somehow)? Similarly can't figure out how 18 works or why exactly it's better than 14. (Also, the snippet for 86 is still missing.)

    @proud-haskeller The top (length 86) snippet seems to be missing. I don't see any instance there.

  • 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:


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

    [email protected]"

    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:


    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:


    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:


    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


    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


    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


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

    Length 23


    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.

    Lets see what you will be able to do with these characters... ;-)

    I would say that it's closer to java than C, actually

    Noted. I think we almost have enough to do some Linq - coming tonight!

    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.

    More snippets please

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


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

    Length 32 snippet


    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


    Creates a new Object.

    Length 25 snippet


    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


    The successor function.

    Length 23 snippet


    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


    Creates an ArrayList with these elements.

    Length 20 snippet


    Prints s.

    Length 19 snippet

    import java.util.*;

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

    Length 18 snippet


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

    Length 17 snippet


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

    Length 16 snippet

    Reads a single character from the console.

    Length 15 snippet


    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


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

    Length 9 snippet


    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


    Ends a statement. Java is weird.

    Length 5 snippet


    Doubles a by subtracting its negation.

    Length 4 snippet


    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.


    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.

    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 Well, the infinite loop causes the statement to be unreachable, which causes the compile error, so it's transitively true.

    @Optimizer Yes - hence the word "often"

    Oh, you are right there. But it would be nice to add an explanation to that single line in your code itself.

    You just got down-voted, I guess this means you'll have to remove a snippet! ;) (The downvote was for "Java is weird")

    Semi-colons are awesome!

    This is exactly why I left Java for other people. So much stuff I had no idea it could be done in it...

    @Ypnypn sometimes endless loops create compiling errors, sometimes they "avoid" them: `String x() {while(true);}` is valid code.

    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.

    Upvoted to help you make a complete program ;)

    -1 for Java. (I upvoted, I promise)

    ClassCastException is not an exception you usually throw.

    `But it Java, [goto] triggers a mysterious RuntimeException` Wrong. `goto` doesn't even compile.

    It should be noted on snippet 31 that this is not a common solution, as often ' and " are on the same key.

    +1 for the `a-=-a` snippet. It just looks so nice.

    @user8397947 The confusion might be because Eclipse allows you to run programs that don't compile - if the rest of the program is well-formed enough, it just replaces whatever it couldn't compile with `throw new RuntimeException("Unresolved compiler error! blah blah blah, more details here")`

  • Python 2

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

    If anyone has suggestions, feel free to comment.

    Length 100

    We reached 100, hurray! Because of this impressive milestone, I have updated this showcase with a new program.

    import re
    def f(i):
    w = re.sub('\s', '', i)
    s = re.subn('[\W_]', '', w)
    a = len(s[0])
    print '%d + %d = %d' % (a, s[1], a+s[1])

    Try it Online!

    Taken from this old answer of mine, which was conveniently 100 bytes.

    This program uses regular expressions on the input string to count the number of whitespace characters, then non-whitespace characters. It will then display the counts, and the sum total. This challenge had a source restriction, requiring the programs to have an equal number of whitespace and non-whitespace characters. Running this program with itself as input will print 50 + 50 = 100.

    re.sub is the function to replace using a regex. re.subn does the same thing, but also returns the number of replacements (in addition to the string after replacement). This program also uses a format string with a tuple of parameters to print in the proper format.

    Length 52:

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

    Taken from my entry in the Fake Marquee Text challenge. s and n need to be set to a string and an integer ahead of time.

    Try It Online!

    Length 43:

    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:

    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

    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 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:


    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:


    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:


    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:


    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:


    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:


    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:


    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:


    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:


    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!

    length 6: it would return `[5, 6, 7, 8, 9, 10]` (the last 6 numbers in the list)

    Length 16: `l` does not have to be a list, it can be any iterable object; tuples, lists and generators for example all work

    @Sp3000: I've used it with [restricted-source] challenges.

    No love for the good old `import antigravity`?

    It's worth noting that several of these do not work in Python 3.x: range(x) returns a generator object in Py3, backticks for `repr()` no longer work, octal literals are now prefaced `0o` instead of `0`. It's probably worth putting these notes in the answer.

    hmm, I don't think it's really **similar to Java and C.** I mean, if it's similar to them, then it's no less similar to C++, LISP, Perl, etc

    @SargeBorsch Why? Just because it doesn't use curly braces? Program design ends up looking similar, assuming you use an object-oriented approach. It's probably closer to JavaScript than those two, though, now that I think about it.

    @mbomb007 Python uses dynamic typing, and is much more high level. Yes, JavaScript would be a closer language, however it implements OO very differently

    You can just use "#coding:rot13" to save 6 characters. The "-*-" is an Emacs-ism.

    This is a showcase, not code-golf.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used