Showcase of Languages

510

340

Notes

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

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

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

How this works

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

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

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

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

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

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

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

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

Current answers, sorted alphabetically by language name

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

Calvin's Hobbies

Posted 2015-01-19T12:36:59.320

Reputation: 84 000

Answers

416

Mathematica

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

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

Length 143 and 144 snippets

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

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

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

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

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

enter image description here

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

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

The resulting animation looks like this:

enter image description here

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

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

Length 100 snippet

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

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

enter image description here

Length 81 snippet

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

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

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

enter image description here

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

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

Length 69 snippet

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

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

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

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

Length 64 snippet

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

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

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

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

enter image description here

Length 59 snippet

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

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

enter image description here

Length 52 snippet

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

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

enter image description here

Length 48 snippet

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

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

Length 45 snippet

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

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

enter image description here

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

enter image description here

Length 44 snippet

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

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

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

enter image description here

Length 43 snippet

HighlightGraph[graph,FindVertexCover@graph]

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

enter image description here

Length 42 snippet

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

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

enter image description here

Length 40 snippet

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

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

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

Length 39 snippet

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

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

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

Length 37 snippet

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

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

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

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

Length 36 snippet

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

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

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

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

Length 35 snippet

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

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

enter image description here

Length 34 snippet

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

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

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

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

Length 33 snippet

Dynamic@EdgeDetect@CurrentImage[]

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

Length 32 snippet

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

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

enter image description here

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

Length 28 snippet

Graphics3D@{Sphere[],Cone[]}

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

enter image description here

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

Length 27 snippet

CountryData["ITA", "Shape"]

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

enter image description here

Length 26 snippet

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

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

enter image description here

Length 25 snippet

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

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

{53, 43, 92}

Length 23 snippet

Rotate[Rectangle, Pi/2]

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

enter image description here

Length 22 snippet

30~ElementData~"Color"

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

SlateGray

Length 21 snippet

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

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

1/2 Sqrt[π] Erf[x]

Length 20 snippet

"Sun"~StarData~"Age"

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

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

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

which is displayed as

enter image description here

Length 19 snippet

MandelbrotSetPlot[]

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

Mathematica graphics

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

Length 18 snippet

PetersenGraph[7,2]

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

Mathematica graphics

Length 17 snippet

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

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

Mathematica graphics

Length 15 snippet

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

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

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

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

We would get

{4,5,1,2,3}

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

Length 12 snippet

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

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

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

Length 9 snippet

Exp[I*Pi]

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

Length 8 snippet

Sunset[]

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

enter image description here

Length 7 snippet

9!/43!!

This snippet shows off a few cool things.

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

128/198893132162463319205625

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

Length 4 snippet

Here

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

Length 3 snippet

x-x

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

Length 2 snippet

3x

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

Length 1 snippet

π

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

Factoid

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

Martin Ender

Posted 2015-01-19T12:36:59.320

Reputation: 184 808

3Awesome though the Sunset function may be, the time it actually returns these days makes me very sad. – overactor – 2015-01-19T14:30:06.190

1RE 22 : Chemestrica – Optimizer – 2015-01-19T19:14:21.123

19Snippet 23 is quite curious. If you did Translate[Scale[Rectangle, 80], {0, 0, 100}] would the huge word Rectangle appear floating in front of your monitor? – Calvin's Hobbies – 2015-01-19T20:41:04.260

54@Calvin'sHobbies Just tried it... picked an unfortunate z offset... smacked me right in the face. – Martin Ender – 2015-01-19T20:44:54.520

Can you prettify the code? Probably with <!-- language-all: lang-js --> since Mathematica isn't supported except on mathematica.stackexchange.com – mbomb007 – 2015-01-20T17:26:07.173

@MartinButtner At least the functions would be a different color. – mbomb007 – 2015-01-20T19:57:53.007

@mbomb007 Just tested it, it looks fairly reasonable. – Martin Ender – 2015-01-20T19:59:32.007

2I wonder how long would be a snippet that searches for a random snippet inside Neat Examples section from Wolfram Documentation :) – swish – 2015-01-21T12:58:22.863

2I assume the next patch will have MathematicaData["Examples",Length] – Ben Jackson – 2015-01-21T17:42:59.180

46The official Mathematica website should absolutely link to this. – Caridorc – 2015-01-21T20:48:28.090

How can you have an exact value for Pi? – durron597 – 2015-01-22T17:08:39.477

7@durron597 By keeping it as a symbol and making all your trigonometric and complex functions aware of what to do with a π. – Martin Ender – 2015-01-22T17:44:45.607

16Once I saw that the legendary Martin Büttner had posted a Mathematica answer, I knew I had no chance at winning a popularity contest. You sir are a true wizard. – Alex A. – 2015-01-23T16:41:34.977

1GeoGraphics[] would be nice for the missing length 13 I think. Show a high quality map of your current location :D – None – 2015-01-23T20:55:19.543

1@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. – Martin Ender – 2015-01-23T20:56:44.830

Many long snippets are missing! – Caridorc – 2015-01-25T20:14:24.967

@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 Ender – 2015-01-25T20:24:35.440

@Martin Butter Awesome,thank you for the dedication! :) – Caridorc – 2015-01-25T20:26:11.120

Nicely done! Have you went through TaP ?

– Vitaliy Kaurov – 2015-01-26T17:32:28.983

@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. – Martin Ender – 2015-01-26T17:33:53.540

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

– Vitaliy Kaurov – 2015-01-26T17:38:18.807

@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! – Martin Ender – 2015-01-26T17:51:06.627

Grats on achieving more +1's than the question itself! – mbomb007 – 2015-02-03T21:57:47.413

4I believe Dynamic@EdgeDetect@CurrentImage[] is a 33 character live webcam edge detector – benwaffle – 2015-02-25T02:56:23.973

@benwaffle Neat! That is actually really nifty, I'll probably include that later. – Martin Ender – 2015-02-25T07:44:11.343

1Now I need to learn Mathematica. Nice post! – ASCIIThenANSI – 2015-05-16T19:40:54.203

Wow, if Mathematica can do all this, why do still people in academia keep insisting to use Matlab? – vsz – 2015-08-17T21:49:31.863

@vsz I actually had to use SageMath with Python. – mbomb007 – 2015-09-02T21:50:27.803

1

I believe that this number I calculated (using Mathematica with nearly all my RAM) would be the rule number for Wireworld.

– LegionMammal978 – 2015-09-26T13:43:17.680

Zero starting point isn't necessary in NDSolve and Animate, you can save two characters in both snippets with {t,60}. Also you can use θ'@0 == φ'@0 == 0 without t->0. Unfortunately, you didn't assign anything to θ and φ, so animation doesn't work without modification of the code. – ybeltukov – 2015-10-31T13:41:02.070

1Time for a length 275 snippet. :D – mbomb007 – 2016-03-17T18:01:29.087

1Can you update it with up to 282? – Rɪᴋᴇʀ – 2016-03-29T13:37:36.103

1But Stephen Wolfram seems to consider himself number-one guy when it comes to cellular automata I laughed a lot with this sentence :-) – Luis Mendo – 2016-04-27T14:21:09.253

I still can't get over that syntax – Cyoce – 2016-04-30T05:45:18.520

What do the @ signs mean? E.g. in Graphics3D@{} – Cyoce – 2016-04-30T05:45:42.960

@Cyoce it's syntactic sugar for Graphics3D[{}], so it's just calling a function with a single argument. – Martin Ender – 2016-04-30T08:05:27.947

@MartinBüttner cool! Kind of weird, but definitely useful for golfing. – Cyoce – 2016-04-30T17:12:31.537

2@Cyoce Also useful for maintainability and readability in actual code. When you just want to apply a bunch of function to an expression you can just prepend f @ g @ h @ expr without having to worry about counting off the right amount of ] to add after expr. Mathematica goes even further there and also allows postfix function application (which is useless of golfing though) so the code reads in the order it's run, e.g. expr // h // g // f for the above example. – Martin Ender – 2016-04-30T17:20:47.483

@MartinBüttner huh. That's even cooler. And stranger :P – Cyoce – 2016-04-30T17:22:25.647

@MartinBüttner Did you buy Mathematica for golfing? – NoOneIsHere – 2016-05-28T23:38:52.700

@NoOneIsHere I have a free licence through my university. (And I also own a Raspberry Pi which is probably the cheapest way to get a Mathematica licence otherwise.) – Martin Ender – 2016-05-29T15:20:13.573

That was very interesting too read. Mathematica sometimes seem to have a built-in for almost anything. Btw, "I think this will be my last snippet, unless I come up with something really mindblowing. Hope you enjoyed this!" Have you come up with something really mindblowing? It can be up to 325 bytes long. :) – Kevin Cruijssen – 2016-08-03T07:01:31.337

@KevinCruijssen I was considering doing something for 300 but it wouldn't have been that novel and I kinda missed that window. Maybe for 400, who knows. No guarantees though. ;) – Martin Ender – 2016-08-03T07:04:06.833

Now that you have 344 upvotes, you should come up with something really mindblowing ;P We are all waiting. – user48538 – 2016-09-22T17:13:10.023

This might be the longest and most elaborate answer on this site. – Hubert Grzeskowiak – 2017-04-20T19:55:20.153

188

The Infamous Shakespeare Programming Language

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

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

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

(link for myself: edit)

Factoid:

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

Length 1 snippet:

I

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

Length 2 snippet:

as

Used in a comparative between two "characters".

Length 3 snippet:

day

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

Length 4 snippet:

rich

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

Length 5 snippet:

Act I

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

Length 6 snippet:

better

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

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

Length 7 snippet:

Juliet:

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

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

Length 8 snippet:

[Exeunt]

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

Length 9 snippet:

as bad as

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

Length 10 snippet:

difference

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

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

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

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

Length 11 snippet:

[Exit Romeo]

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

Length 12 snippet:

Remember me.

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

Length 13 snippet

Let us return

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

Length 14 snippet

my little pony

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

Length 15 snippet

Speak thy mind!

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

Length 16 snippet

You are nothing!

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

Length 17 snippet

Ophelia, a wench.

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

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

Length 18 snippet

lying sorry coward

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

Length 19 snippet

Romeo:
 Remember me.

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

Length 20 snippet

cube of thy codpiece

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

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

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

Length 21 snippet

Listen to your heart.

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

Length 22 snippet

Recall your childhood!

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

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

Length 23 snippet

Are you better than me?

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

Length 24 snippet

[Enter Romeo and Juliet]

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

Length 25 snippet

remainder of the quotient

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

Length 26 snippet

Let us return to scene II.

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

Length 27 snippet

[Exeunt Ophelia and Hamlet]

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

Length 28 snippet

Scene I: Ophelia's flattery.

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

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

Length 29 snippet

You pretty little warm thing!

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

Length 30 snippet

You are as cowardly as Hamlet!

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

Factoid (yes, another landmark reached!)

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

Length 31 snippet

Am I as horrid as a flirt-gill?

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

Length 32 snippet

If so, let us return to scene I.

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

Length 33 snippet

If not, let us return to scene I.

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

Length 34 snippet

Open your mind! Remember yourself.

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

Length 35 snippet

Act I: Death!

Scene I: Oh, shit.

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

Length 36 snippet

Thou art as sweet as a summer's day!

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

Length 37 snippet

Art thou more cunning than the Ghost?

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

Length 38 snippet

[Enter the Ghost, Romeo and the Ghost]

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

Length 39 snippet

the sum of a fat lazy pig and yourself!

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

Length 40 snippet

the sum of a squirrel and a white horse.

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

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

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

Length 41 snippet

Juliet:
 Speak thy mind!

[Exit Romeo]

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

Length 42 snippet

Speak YOUR mind! You are as bad as Hamlet!

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

Length 43 snippet

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

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

Length 44 snippet

You are as evil as the square root of Romeo!

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

Length 45 snippet

Hamlet:
 Art thou more cunning than the Ghost?

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

Length 46 snippet

the product of a rural town and my rich purse.

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

Length 47 snippet

Romeo:
 Speak your mind.

Juliet:
 Speak YOUR mind!

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

Length 48 snippet

You lying fatherless useless half-witted coward!

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

Length 49 snippet

Scene V: Closure.

Hamlet:
 Speak your mind!

[Exeunt]

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

Length 50 snippet

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

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

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

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

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

Length 51 snippet

Othello:
 Recall your great dreams. Speak your mind!

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

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

Length 52 snippet

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

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

Length 53 snippet

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

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

Length 54 snippet

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

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

Length 55 snippet

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

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

Length 56 snippet

Othello:
 You lying fatherless useless half-witted coward!

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

Length 57 snippet

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

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

Length 58 snippet

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

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

Length 59 snippet

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

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

Length 60 snippet

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

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

Length 61 snippet

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

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

Length 62 snippet

twice the difference between a mistletoe and a oozing blister!

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

Length 63 snippet

You lying stupid fatherless rotten stinking half-witted coward!

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

Length 64 snippet

your coward sorry little stuffed misused dusty oozing rotten sky

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

Length 65 snippet

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

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

Length 66 snippet

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

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

Length 67 snippet

Juliet:
 Am I better than you?

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

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

Length 68 snippet

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

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

Length 69 snippet

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

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

Length 70 snippet

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

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

Length 71 snippet

Scene I: Dialogues.

[Enter Juliet]

Othello:
 Speak your mind!

[Exit Juliet]

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

Length 72 snippet

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

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

Length 73 snippet

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

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

Length 74 snippet

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

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

Length 75 snippet

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

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

Length 76 snippet

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

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

Length 77 snippet

[Exit Hamlet]

[Enter Romeo]

Juliet:
 Open your heart.

[Exit Juliet]

[Enter Hamlet]

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

Length 78 snippet

The Ghost:
 Speak thy mind.

Lady Macbeth:
 Listen to thy heart! Remember thyself.

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

Rodolfo Dias

Posted 2015-01-19T12:36:59.320

Reputation: 3 940

32This incredibly interesting and your profile picture is a perfect fit, he looks precisely like what I imagine an SPL programmer would look like. – overactor – 2015-01-22T09:34:16.800

3@overactor I don't know whether to be insulted or proud to be likened to a Gumby. ^_^ – Rodolfo Dias – 2015-01-22T09:59:55.073

Which number system did you use for the calculation 2*2*(-1) = -6? – Nobody – 2015-01-22T13:19:06.053

@Nobody A system only I know, apparently... (yes, it was an error, meanwhile corrected) – Rodolfo Dias – 2015-01-22T13:41:55.680

9Bizarrely this is NOT the most obscure to read example here... and seems to be tied for "least practical". – H.R.Rambler – 2015-01-23T16:46:30.653

@H.R.Rambler "Least practical", you say? Wait until I begin with arithmetic operations (if I get more 100 upvotes, of course)... – Rodolfo Dias – 2015-01-23T23:15:30.607

6ROFL here's +1 to help you on the way - Once more unto the breach Rodolfo! – H.R.Rambler – 2015-01-24T14:31:37.487

2Wish I could upvote more than once... This is interesting stuff. – GloriaVictis – 2015-01-25T18:18:34.830

3@RodolfoDias You can begin. I'm waiting to see them. You have 120 up-votes. – ghosts_in_the_code – 2015-11-13T15:52:57.250

2

Only 6239986 votes to go for a quine.

– Flogo – 2016-05-05T12:48:33.523

Can we have more snippets? – OldBunny2800 – 2016-11-26T15:50:44.827

Does SE seriously has support for SPL code highlighting? Does anyone use this programming language in reality? Or they did it for fun? – RedClover – 2017-10-23T16:23:26.100

"Not better" should be <=, not <. – user202729 – 2018-05-28T02:42:48.490

+1 for my little pony. – HighlyRadioactive – 2019-09-27T13:41:21.293

176

Piet

Factoid

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

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

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

1 Codel

1 Codel

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

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

2 Codels

2 Codels

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

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

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

3 Codels

3 Codels

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

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

4 Codels

4 Codels

Prints out 2 to stdout indefinitely.

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

5 Codels

5 Codels

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

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

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

6 Codels

6 Codels

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

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

7 Codels

7 Codels

Yet another echo program with a different look.

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

8 Codels

8 Codels

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

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

9 Codels

9 Codels

Adds 1 + 2 = 3, and then terminates.

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


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

12 Codels

12 Codels

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

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

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

15 Codels

15 Codels

Reads a number from stdin and outputs its' square.

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

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

20 Codels

20 Codels

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

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

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

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

25 Codels

25 Codels

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

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

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

30 Codels

30 Codels

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

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

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

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

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

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

The yellow pattern in the middle is never used.

54 Codels

54 Codels

Prints "hi!" to stdout

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

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

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

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

Spencer

Posted 2015-01-19T12:36:59.320

Reputation: 1 676

5Hah yes, was waiting for this :) – Sp3000 – 2015-01-20T03:09:00.563

How's that any different from a 2D character language? It's just the way you convey the cell values. – JDługosz – 2015-01-20T03:31:08.477

26@jdlugosz Many esoteric programming languages, when you get down to it, are just a few basic stack manipulation commands with a unique way of encoding the commands. I personally think encoding them in an image is a neat idea. – Spencer – 2015-01-20T04:00:13.117

13If we're talking functional equivalence, you could ask "How's that any different from a Turing machine?" but then you could level that same question at a cat, or the planet Jupiter, or any of the other languages... – trichoplax – 2015-01-20T05:37:36.997

Could you explain what each codel in each image does individually? This is harder to understand than ><>. – mbomb007 – 2015-01-20T19:10:18.390

@mbomb007 I've updated the descriptions on most of the programs to add more detail, hopefully it's clearer now. – Spencer – 2015-01-20T23:27:28.673

3The 9 codel example looks like a mini-pokeball. Nice. – The_Basset_Hound – 2015-08-24T01:23:10.113

154

><> (Fish)

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

Factoid:

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

Length 1 snippet:

X

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

Length 2 snippet:

1n

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

Length 3 snippet:

"o;

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

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

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

Length 4 snippet:

42n;

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

Length 5 snippet:

<v
;>

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

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

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

Length 6 snippet:

";"00p

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

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

Length 7 snippet:

\7*n;
6

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

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

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

Length 8 snippet:

"r00g>o<

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

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

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

Length 9 snippet:

x0\>
\1n>

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

Length 10 snippet:

;a comment

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

Length 11 snippet:

1!X2!X+!Xn;

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

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

Length 12 snippet:

01v
ao>:@+:n

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

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

Trace for the first few iterations:

enter image description here

Length 13 snippet:

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

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

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

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

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

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

Length 14 snippet:

32.

   X67*n;

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

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

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

Length 15 snippet:

01+:aa*=?;:nao!

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

Length 16 snippet:

"r00g!;oooooooo|

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

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

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

'r3d*!;oooooooo|

Length 17 snippet:

b2,63,.

   17,n;

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

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

Length 18 snippet:

123456${{$}nnnnnn;

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

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

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

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

Then we output, giving 256431.

Length 19 snippet:

"reward"4[roooo]oo;

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

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

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

Here's the trace for the above program:

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

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

Length 20 snippet:

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

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

The above code is functionally the same as

aa*5+7a*2+oo;

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

Length 22 snippet:

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

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

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

enter image description here

Length 24 snippet:

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

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

Length 25 snippet:

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

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

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

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

Length 33 snippet:

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

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

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

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

enter image description here

Length 44 snippet:

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

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

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

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

Length 74 snippet:

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

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

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

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

Sp3000

Posted 2015-01-19T12:36:59.320

Reputation: 58 729

An idea for the 13 snippet: i:d=?v NEWLINE o;!?l< -- prints input line backwards – tomsmeding – 2015-01-19T17:29:15.210

12I wish I could give this more up votes, I am now inspired to begin learning ><>... – Robobenklein – 2015-01-20T15:19:14.750

6+1 for starting at top and going down (and also just because it's fun to read). – mbomb007 – 2015-01-20T19:01:49.330

5@mbomb007 it's a shame, though, that the order can't go left/right and wrap to the bottom of the page :P – krs013 – 2015-01-30T05:14:10.757

Your length 8 snippet would be a true quine if you wrote something smells fishy... on the next line. – wizzwizz4 – 2016-01-17T16:30:14.543

147

C – edit

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

So why feature C?

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

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

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

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

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

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

Factoid

C rocks.

Length 0 snippet

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

Length 1 snippet

;

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

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

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

Length 2 snippet

x;

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

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

Length 3 snippet

??/

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

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

Length 4 snippet

f();

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

Note the fundamental differences between this and f;.

Length 5 snippet

s="";

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

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

Length 6 snippet

o=042;

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

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

Length 7 snippet

f(){f;}

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

Length 8 snippet

main(){}

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

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

Length 9 snippet

#define Z

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

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

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

Length 10 snippet

enum{P,Q};

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

Length 11 snippet

volatile v;

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

Length 12 snippet

#pragma once

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

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

Length 13 snippet

w(){for(;;);}

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

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

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

Length 14 snippet

int a[]={1,2};

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

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

Length 15 snippet

const long k=7;

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

Length 16 snippet

extern void **q;

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

Length 17 snippet

double d=4/3-1/3;

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

Length 18 snippet

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

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

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

Length 19 snippet

#include <stdlib.h>

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

Length 20 snippet

char*p=(char*)0x300;

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

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

Length 21 snippet

int w=sizeof(double);

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

Length 22 snippet

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

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

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

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

Length 23 snippet

union u{char c;int i;};

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

Length 24 snippet

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

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

Length 25 snippet

int main(void){return 1;}

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

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

Length 26 snippet

typedef struct{int x,y;}P;

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

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

Length 27 snippet

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

C has a convenient macro #define syntax.

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

Length 28 snippet

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

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

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

Length 36 snippet

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

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

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

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

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

Length 48 snippet

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

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

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

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

Length 51 snippet

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

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

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

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

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

Length 63 snippet

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

Or formatted more sanely:

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

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

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

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

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

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

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

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

static int q = w;
static int w;

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

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

static int w;
static int q = w;

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

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

Length 74 snippet

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

Or laid out nicely:

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

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

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

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

Length 88 snippet

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

Or with a saner layout:

#include <stdio.h>

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

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

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

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

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

f(12)

Becomes:

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

Without any function calls required!

Other compilers can reorganize the function:

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

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

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

Length 117 snippet

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

Or:

#include <stdio.h>

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

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

    return 0;
}

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

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

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

Length 132 snippet

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

Or:

#include <stdio.h>

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

    return 0;
}

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

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

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

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

user15259

Posted 2015-01-19T12:36:59.320

Reputation:

4I don't think that there was a requirement to add a new factoid for each upvote :) – Optimizer – 2015-01-19T17:58:17.893

@Optimizer - Until I can get into some actual compile-and-link code, I'll add an explanation for those more familiar with scripting languages. – None – 2015-01-19T18:00:15.983

That can take a whiiile – Optimizer – 2015-01-19T18:01:13.147

29A common culture in C is to ignore compilation warnings, I don't think this is anywhere near the truth! – Shahbaz – 2015-01-19T18:57:35.230

4If you have a large project and consider multiple compilers, it can be quite futile to try to eliminate all warnings. – feersum – 2015-01-19T20:06:02.310

1Wrt #7, gcc will not automatically return 0; usually you get some garbage value. – feersum – 2015-01-19T20:08:41.887

"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 – 2015-01-20T22:52:33.707

@user19057 - thanks for catching that, corrected. – None – 2015-01-21T03:19:30.147

@feersum - after confirmation, #7 revised, thank you. – None – 2015-01-21T03:35:09.073

suggestion: do something with the "complex" datatype – Jasen – 2015-01-22T11:13:05.367

Thank you. Just letting what I wrote pass public opinion before I continue. Also looking at the C99 exception handling which almost everyone ignores! – None – 2015-01-22T14:50:17.797

For #8 : the shortest compilable and linkable program is actually main;, which however crashes at runtime. – Quentin – 2015-01-22T22:11:25.810

#18 puts is a macro defined in stdio.h fputs deosn't require a header. – Jasen – 2015-01-24T05:33:55.270

@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(){}! – None – 2015-01-26T18:36:35.893

@Jasen - I guess it depends on distribution. In gcc, no macros in <stdio.h>. Too many problems with macros, in particular address of to use in callbacks. – None – 2015-01-26T18:42:45.817

5This is excellent – Kik – 2015-01-27T21:05:18.537

1As a developer who began with C myself (before moving to Python, and not counting Visual Basic), I can confirm that Haskell freaks me out. – Joe Z. – 2015-04-06T19:36:11.993

2Can we talk about code snippet 0. Which points to a copyrighted quine that has no code it in. Does that mean they copyrighted null??? – Sahar Rabinoviz – 2015-10-18T02:40:11.453

@DisplayName101 - haha - he should be claiming payment on the infinite copies everyone has of this program! – None – 2015-11-10T15:02:08.297

@Kik Am I the only one who thought of Mr Burns when I saw that comment? – DJgamer98 – 2015-11-17T10:23:30.667

4I'm a C programmer, and I'm not scared of Haskell. – Shahbaz – 2016-03-28T21:58:16.760

1FYI: OOP has nothing to do with operator overloading, a language can be object oriented without it. – YoYoYonnY – 2016-05-15T00:32:26.090

So what about volatile const? I can guess a useful interpretation that it might have, but I don't know if it is correct. – Christian Sievers – 2017-08-18T09:42:42.000

@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. – None – 2017-08-19T12:45:04.297

138

x86 Machine Code

Factoid:

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

Length 1:

Now for the first program:

0xC3

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

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

Length 2:

Our next program:

0x4D 0x5A

or 'MZ' in ASCII.

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

DEC     BP
POP     DX

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

Length 3:

Now for an infinite loop:

41 E2 FD

Which translates to

start:
inc cx
loop start 

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

Length 4:

A program that is minimally useful:

40 CD 10 C3

Translated to assembly:

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

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

Length 5:

We can now implement a pause program:

B4 01 CD 21 C3

Translated to assembly:

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

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

Length 9:

Now to actually display output:

68 00 B7 07 AB 40 79 FC C3

Translated to assembly:

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

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

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

Length 20:

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

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

In assembly:

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

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

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

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

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

jmp     start   ; 2b - infinite loop

Sample output: Sierpinski Triangles

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

Length 21

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

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

Translated to assembly:

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

Sample output:

c:\misc>cpuid.com
GenuineIntel

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

Length 26

We can now do interesting animations

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

In Assembly

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

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

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

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

And the output will look like this:

Marching XOR

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

Length 27

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

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

In assembly:

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

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

Length 29

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

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

Translated to assembly:

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

Output:

Dragon Curve

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

Length 52

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

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

When run, the program will output several mathematical constants:

1.00000000000000000
3.32192809488736235
1.44269504088896341
3.14159265358979324
0.30102999566398120
0.69314718055994531
0.00000000000000000

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

In assembly:

org 100h

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

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

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

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

convert:
lodsb                ;load a pair of packed digits

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

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

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

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

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

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


ten: dw  10

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

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

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

Length 64

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

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

In assembly:

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

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

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

xor bx,bx
xor si,si

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

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

loop MandelLoop

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

The end result is this image:

Mandelbrot Fractal

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

Sir_Lagsalot

Posted 2015-01-19T12:36:59.320

Reputation: 4 898

7Of all of the languages to see on PPCG, I did not expect this. – Alex A. – 2015-01-27T00:58:54.407

23Wow.

Plus other characters to make this a comment. But seriously. Wow. – krs013 – 2015-01-27T08:29:25.870

this takes me back a ways! Too bad I can no longer hand-edit .com files in 64-bit Windows 8 :\ – KutuluMike – 2015-01-29T17:05:33.170

2@Michael Edenfield That's what DOSBox is for! – Sir_Lagsalot – 2015-01-29T20:22:13.930

120 byte Sierpinski is very impressive. – qwr – 2016-04-08T21:48:28.193

1I consider myself to be a good programmer, but when I look at this I must admit defeat. – Stephan Bijzitter – 2016-09-29T21:51:51.553

122

Haskell

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

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

Length 86 snippet

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

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

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

and so on.

Here's a picture of our tree:

7
| \
3  5
    \
     8

Length 70 snippet

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

This is a prime sieve!

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

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

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

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

Length 68 snippet

Finally, a quine!

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

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

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

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

Length 33 snippet:

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

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

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

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

Length 26 snippet:

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

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

How did it know?? ;-)

Length 25 snippet:

main=putStr"Hello World"

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

Length 23 snippet:

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

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

(see snippet 10)

Let's break it down:

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

Length 22 snippet:

main=putStrLn"y">>main

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

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

Length 18 snippet:

fix f=r where r=f r

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

Length 17 snippet:

f n=product[1..n]

This is the functional way to define factorial.

Length 16 snippet:

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

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

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

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

Length 15 snippet:

sum=foldl (+) 0

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

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

Length 14 snippet:

fix f=f(fix f)

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

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

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

Length 13 snippet:

f=sum.map(^2)

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

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

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

Length 10 snippet:

data B=T|F

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

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

Length 9 snippet:

main=main

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

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

Length 8 snippet:

f(x:_)=x

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

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

The patterns in this snippet are:

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

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

Length 5 snippet:

x=2:x

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

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

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

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

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

Length 4 snippet:

2:[]

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

Length 3 snippet:

f.g

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

Length 2 snippet:

1-

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

Length 1 snippet:

1

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

factoid:

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

proud haskeller

Posted 2015-01-19T12:36:59.320

Reputation: 5 866

i don't know if i should replace the factoid with the fact that Haskell has the most function/operators in it's standard library which generate functions from other functions (and that technically every two or more parameter function is such). should I? – proud haskeller – 2015-01-19T13:49:14.393

Show it off in a snippet and add it in the explanation. – Martin Ender – 2015-01-19T14:12:44.420

f=0:1:zipWith(+)f(tail f) -- 25 chars, a functions that returns a lazy-calculated list of the Fibonacci numbers. – chamini2 – 2015-01-20T03:06:38.357

ugh i added a bunch of snippets and then my computer shut down – proud haskeller – 2015-01-20T18:42:09.157

@proudhaskeller Saving op. I've never done this personally, but if you have a large edit to do at once, you could perform the edit in an external document with saving, then paste it in when it's complete. – mbomb007 – 2015-01-20T19:00:37.223

You should update this! More ideas: a typeclass instance for your tree type, polymorphic recursion, Fix, filterM powerset, primes, quine? – Lynn – 2015-08-25T21:40:06.313

@Lynn feel free to add some of your own, and edit the existing ones, I just don't have enough time. – proud haskeller – 2016-04-02T13:48:56.780

In the length 38 snippet, you say you define a foldr, but where is it defined? – Brian McCutchon – 2017-04-21T00:40:37.470

@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 – proud haskeller – 2017-04-22T15:05:30.447

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.) – sundar - Reinstate Monica – 2018-07-02T10:27:55.573

100

C#

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

I'll ignore the usual required boilerplate:

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

Length 1:

;

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

Length 5:

x=5f;

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

Length 7 (bytes):

s=@"
";

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

Length 8:

()=>x=y;

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

Length 9:

(a)=>a.p;

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

Length 10:

enm.Any();

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

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

Length 11:

var a=1.5f;

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

Length 15:

yield return 0;

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

Length 16:

[Obsolete]int a;

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

Length 17

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

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

Length 18:

foreach(T t in c);

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

Length 19

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

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

Length 21

Console.Write("Hi!");

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

Length 23

typeof(T).GetMethods();

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

Length 25

from t in c select t.a/2;

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

Length 27

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

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

Length 29

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

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

Length 31

public int pr{get;private set;}

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

Length 32

public static void m(this T o){}

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

Length 38

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

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

Length 42

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

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

Length 48

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

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

Length 56

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

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

Length 65

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

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

BMac

Posted 2015-01-19T12:36:59.320

Reputation: 2 118

1Lets see what you will be able to do with these characters... ;-) – proud haskeller – 2015-01-20T16:19:42.217

9I would say that it's closer to java than C, actually – proud haskeller – 2015-01-20T16:20:36.547

Noted. I think we almost have enough to do some Linq - coming tonight! – BMac – 2015-01-20T21:36:12.357

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. https://msdn.microsoft.com/en-us/library/85w54y0a.aspx

– Zukki – 2015-07-21T13:48:17.430

More snippets please – Cyoce – 2016-10-02T05:53:10.637

98

Java


Length 44 snippet

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

Prints Hello, World! to STDOUT.

Length 43 snippet

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

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

Length 42 snippet

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

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

Length 36 snippet

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

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

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

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

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

Length 35 snippet

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

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

Length 34 snippet

public static void main(String[]a)

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

Length 33 snippet

enum D {NORTH, EAST, SOUTH, WEST}

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

Length 32 snippet

Files.readAllBytes("hello.txt");

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

Length 31 snippet

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

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

Length 30 snippet

new JFrame().setVisible(true);

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

Length 29 snippet

throws ClassNotFoundException

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

Length 28 snippet

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

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

Length 27 snippet

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

Creates a new array of strings.

Length 26 snippet

Object.class.newInstance()

Creates a new Object.

Length 25 snippet

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

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

Length 24 snippet

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

The successor function.

Length 23 snippet

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

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

Length 22 snippet

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

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

Length 21 snippet

Arrays.asList(2L,"a")

Creates an ArrayList with these elements.

Length 20 snippet

System.out.print(s);

Prints s.

Length 19 snippet

import java.util.*;

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

Length 18 snippet

Math.addExact(x,y)

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

Length 17 snippet

Double.MIN_NORMAL

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

Length 16 snippet

System.in.read()

Reads a single character from the console.

Length 15 snippet

Long.reverse(x)

Reverses the bits in the binary representation of x.

Length 14 snippet

int x=050+120;

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

Length 13 snippet

private C(){}

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

Length 12 snippet

static class

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

Length 11 snippet

throw null;

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

Length 10 snippet

int[]a,b[]

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

Length 9 snippet

switch(x)

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

Length 8 snippet

break a;

Breaks out of the block labeled a.

Length 7 snippet

goto x;

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

Length 6 snippet

\u003b

Ends a statement. Java is weird.

Length 5 snippet

a-=-a

Doubles a by subtracting its negation.

Length 4 snippet

a&=b

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

Length 3 snippet

...

Any number of arguments, consolidated into an array.

Length 2 snippet

<>

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

Length 1 snippet

@

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

Factoid

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

Ypnypn

Posted 2015-01-19T12:36:59.320

Reputation: 10 485

5In 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 – 2015-01-19T17:48:16.893

@Optimizer Well, the infinite loop causes the statement to be unreachable, which causes the compile error, so it's transitively true. – Ypnypn – 2015-01-19T19:28:23.913

@Optimizer Yes - hence the word "often" – Ypnypn – 2015-01-19T19:33:58.610

Oh, you are right there. But it would be nice to add an explanation to that single line in your code itself. – Optimizer – 2015-01-19T19:35:36.193

4You just got down-voted, I guess this means you'll have to remove a snippet! ;) (The downvote was for "Java is weird") – Simon Forsberg – 2015-01-19T20:56:03.210

Semi-colons are awesome! – mbomb007 – 2015-01-20T19:13:32.200

This is exactly why I left Java for other people. So much stuff I had no idea it could be done in it... – Rodolfo Dias – 2015-01-22T08:08:27.477

@Ypnypn sometimes endless loops create compiling errors, sometimes they "avoid" them: String x() {while(true);} is valid code. – Fabio F. – 2015-01-22T16:18:33.350

1It seems that the snippet #36 is recursive and can be extended indefinitely: class A{class B extends A{B.B.B.B.B.B.B b;}} still compiles. – Natix – 2015-01-28T13:18:38.810

3Upvoted to help you make a complete program ;) – durron597 – 2015-01-28T19:32:35.383

-1 for Java. (I upvoted, I promise) – cat – 2016-04-28T19:32:29.947

ClassCastException is not an exception you usually throw. – Bálint – 2016-05-06T15:05:10.113

1But it Java, [goto] triggers a mysterious RuntimeException Wrong. goto doesn't even compile. – user8397947 – 2016-06-25T02:35:53.563

@durron597 Done!

– user8397947 – 2016-07-12T02:29:17.677

It should be noted on snippet 31 that this is not a common solution, as often ' and " are on the same key. – None – 2016-09-21T03:15:10.527

+1 for the a-=-a snippet. It just looks so nice. – HyperNeutrino – 2016-10-28T00:58:47.883

93

Python

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

If anyone has suggestions, feel free to comment.

Length 52:

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

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

Length 43:

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

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

Here it is translated:

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

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

Length 33:

import cmath
print cmath.sqrt(-1)

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

Length 30:

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

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

Length 29:

import math
math.factorial(7)

Finds the factorial of 7, returning 5040.

Length 25:

import math
print math.pi

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

Length 24:

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

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

Length 19:

print"Hello World!"

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

Length 16:

[x*3 for x in l]

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

Length 15:

import this #:)

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

Length 14:

lambda x:x**.5

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

Length 13:

1 if x else 0

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

Length 12:

s=input(">")

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

Length 11:

eval("2e3")

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

Length 10:

range(013)

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

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

Length 9:

a,b = b,a

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

Length 8:

#comment

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

Length 7:

l[::-1]

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

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

Length 6:

l[-6:]

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

Length 5:

1<x<5

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

Length 4:

0256

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

Length 3:

`3`

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

Works in Python 2 only!

Length 2:

[]

An empty list.

Length 1:

_

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

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

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

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

mbomb007

Posted 2015-01-19T12:36:59.320

Reputation: 21 944

Anytime! I'm not gonna add anymore snippets (couldn't resist the Length 9 one!), since you're doing a great job with it already. Good luck! – nasser-sh – 2015-01-22T14:39:29.370

1length 6: it would return [5, 6, 7, 8, 9, 10] (the last 6 numbers in the list) – Vincent – 2015-01-23T13:18:45.720

Length 16: l does not have to be a list, it can be any iterable object; tuples, lists and generators for example all work – nasser-sh – 2015-01-23T17:16:54.580

@Sp3000: I've used it with [restricted-source] challenges. – Robbie Wxyz – 2015-02-02T18:54:35.680

4

No love for the good old import antigravity?

– Cipher – 2015-10-22T15:00:22.677

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. – Mathime – 2016-08-14T13:04:43.947

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 – Display Name – 2016-09-03T15:18:15.267

@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 – 2016-09-06T15:14:00.147

@mbomb007 Python uses dynamic typing, and is much more high level. Yes, JavaScript would be a closer language, however it implements OO very differently – Display Name – 2016-09-07T02:15:10.940

You can just use "#coding:rot13" to save 6 characters. The "-*-" is an Emacs-ism. – Mathias Rav – 2017-05-06T23:21:58.907

This is a showcase, not code-golf. – mbomb007 – 2017-05-07T19:52:47.823

87

JavaScript

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

Length 51 snippet:

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

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

Length 50 snippet:

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

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

Length 49 snippet:

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

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

Length 48 snippet:

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

Simulate setInterval by recursively setTimeouting.

Length 47 snippet:

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

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

Length 46 snippet:

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

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

Length 45 snippet:

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

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

Length 44 snippet:

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

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

Length 43 snippet:

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

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

Length 42 snippet:

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

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

Length 41 snippet:

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

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

Length 40 snippet:

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

We are totally dropping those paragraphs and using jQuery.

Length 39 snippet:

script=document.createElement('script')

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

Length 38 snippet:

document.getElementsByClassName('abc')

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

Length 37 snippet:

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

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

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

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

Length 36 snippet:

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

A quine. It prints its own source code.

Length 35 snippet:

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

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

Length 34 snippet:

Object.prototype.toString.call(34)

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

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

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

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

Length 32 snippet:

document.body.innerHTML="hacked"

Halp! Hazxxors!eleven!!11!

Length 31 snippet:

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

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

Length 30 snippet:

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

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

Length 29 snippet:

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

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

Length 28 snippet:

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

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

Length 27 snippet:

document.querySelector('a')

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

Length 26 snippet:

JSON.stringify({twenty:6})

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

Length 25 snippet:

new Badge("Good Answer");

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

Length 24 snippet:

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

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

Length 23 snippet:

window.parent==self.top

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

Length 22 snippet:

for(i in self)alert(i)

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

Length 21 snippet:

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

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

Length 20 snippet:

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

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

Length 19 snippet:

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

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

Length 18 snippet:

location.href="/";

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

Length 17 snippet:

(function(){})()

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

Length 16 snippet:

obj={not:'json'}

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

Length 15 snippet:

open('//s.tk/')

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

Length 14 snippet:

function f(){}

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

Length 13 snippet:

Math.random()

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

Length 12 snippet:

new Date<=12

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

Length 11 snippet:

Math.PI*121

The area of a circle with radius 11.

Length 10 snippet:

if('j')9+1

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

Length 9 snippet:

[9].pop()

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

Length 8 snippet:

document

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

Length 7 snippet:

alert()

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

Length 6 snippet:

var x=6

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

Length 5 snippet:

[][5]

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

Length 4 snippet:

+"4"

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

Length 3 snippet:

x=3

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

Length 2 snippet:

{}

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

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

Length 1 snippet:

1

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

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

Scimonster

Posted 2015-01-19T12:36:59.320

Reputation: 2 905

1Snippet 33 doesn't work on Firefox. Is it really valid JS? – Oriol – 2015-01-24T01:25:55.140

I find stringifying and reparsing an object to copy it so dirty. ECMAScript 6 introduces Object.assign, so snippet 37 becomes b = Object.assign({ }, a = {3 : 7}).

– Oriol – 2015-01-25T10:37:10.350

@Oriol Yes, well, only Firefox supports it right now, so we have to stick to the dirty way for now. At least it's better than eval(uneval(a)), right? ;) – Scimonster – 2015-01-25T12:22:54.297

About #38, there's always document.querySelectorAll("element#id.classname[attribute]:not(somethingwedontwant)"). (Supports any valid CSS selector). – Mateon1 – 2015-01-26T16:46:36.510

The #40 snippet itself isn't so interesting, but the comment is priceless. – Scimonster – 2015-01-27T08:45:28.593

"It takes advantage of the fact that elements with IDs are populated as global variables" - not in Firefox ;) – Qwertiy – 2015-03-18T21:14:23.690

I think you missed label:, NaN===NaN and of course Array(16).join('wat' -1) + " Batman!" – Jonathan – 2015-09-28T19:55:49.270

This answer now has a score of 73, could you update it? – Michał Perłakowski – 2016-04-11T18:53:21.227

Snippet 33 doesn't work in chrome either D: Uncaught SyntaxError: Keyword must not contain escaped characters – Brian H. – 2017-11-23T11:57:42.737

The length 6 snippet appears to be 7 characters – fəˈnɛtɪk – 2019-01-04T22:42:06.403

85

R

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

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


Length 32:

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

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

swiss[3, 2, drop = FALSE]

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

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

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

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

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

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

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


Length 31:

print(fortune("hadleywickham"))

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

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

Length 30:

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

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

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

enter image description here


Length 29:

summary(lm(mag~depth,quakes))

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

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

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

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

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

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

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

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

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

Coefficients:
              Estimate Std. Error t value Pr(>|t|)    
(Intercept)  4.755e+00  2.179e-02 218.168  < 2e-16 ***
depth       -4.310e-04  5.756e-05  -7.488 1.54e-13 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.3921 on 998 degrees of freedom
Multiple R-squared:  0.05319,   Adjusted R-squared:  0.05225 
F-statistic: 56.07 on 1 and 998 DF,  p-value: 1.535e-13

Notice how the first thing it tells you is the function call? That's because the lm() function uses match.call(), just like we did in snippet 28!


Length 28:

f<-function(x,y)match.call()

R functions often like to keep track of what you tell them. Indeed, sometimes the command you've submitted is given back to you as an attribute of the returned object. (An example is lm(), which creates linear models.) Recalling the precise instructions is accomplished using match.call() within the function. This captures, or matches, the interpreted function call.

Here we've defined a function f() that takes two arguments and then tells you what it saw.

> f(1,2)
f(x = 1, y = 2)

This is primarily useful when developing functions for general use (rather than just for you), like in package development. If you want to see an example of match.call() in the wild, look at the source code for lm() by submitting stats:::lm. One of the first things it does is capture the function call using match.call().


Length 27:

install.packages("ggplot2")

This may seem trivial, but it shows one of the reasons why R is so popular: It's very easily extensible through packages. And anyone can develop and freely share their packages!

install.packages() does precisely what its name suggests. It goes a-huntin' for packages using your default CRAN (Comprehensive R Archive Network) mirror then installs them on your system where R can find them. You can also have it install packages from local source code.

Remember snippet 23 where we used the ggplot2 package? That package does not ship with R, but in just 27 characters you can make all of your ggplot2 dreams come true by installing it.


Length 26:

filled.contour(t(volcano))

The volcano dataset ships with R. It's a matrix containing topographic information on the Maungawhau (or Mt. Eden) volcano in Auckland, New Zealand. The rows of the matrix correspond to grid lines running east to west and the columns are grid lines running south to north.

For the sake of disorientation, let's swap the directions, so columns are now east-west and rows are south-north. We can do this using a matrix transpose, accomplished via t(). And why not make a contour map while we're at it? filled.contour() does just that.

enter image description here


Length 25:

pmatch("s",c("n","size"))

The pmatch() function provides the magic behind all the partial matching we've seen so far. The first argument is a string which is compared against each element of the second argument, a vector. If there's a unique match, the index of the matching element is returned, otherwise you get NA.

The snippet here is a "real-world" example of the use of this function. Think back to snippet 13 where we used the sample() function. It accepts arguments n, size, replace, and prob, but only requires the first two. In snippet 13 we used s= as shorthand for size=. What's actually going on in the background is something like this snippet, where what we've provided is compared against what's expected. Since "s" matches "size" uniquely, it's totally legit to use s= as shorthand.


Length 24:

`(`=function(x)9;2*(3-1)

A perfect example of something you shouldn't do! Ever!

You can assign characters as functions so long as you surround them in back ticks when defining the function. Here we told R that ( is a function that always returns 9 regardless of the input. Like in many other languages, ; can be used for including two commands on one line. So what we've told R is to define the function (, then print 2*(3-1).

Now, just about any person would tell you that 2*(3-1) should be 4 because you do 3-1=2, then 2*2=4. But we've told R that anything inside parentheses is 9. So while 3-1=2, we now have (3-1)=9. Then we get 2*(3-1) = 2*9 = 18.

Since awful things like this are possible, every time you submit code that contains parentheses in an expression (i.e. not a function call), the R interpreter actually goes looking for any functions called ( regardless of whether you've defined ( as a function. In general, the more you write, the more work the R interpreter does.


Length 23:

qplot(Na,y=RI,data=fgl)

Finally enough votes for a (very) simple ggplot2 example. The ggplot2 package is an R implementation of the Grammar of Graphics, created by the legendary R deity Hadley Wickham. In general the syntax is very different from the base R graphics and takes some getting used to. However, qplot() is a simpler interface to some of the core features of the package and has syntax akin to plot() in base R. But unlike many of the examples I've shown you, qplot() does not support partial matching of function parameter names.

The fgl dataset comes from the MASS package. It contains measurements of properties of forensic glass fragments. Here we're using the variables Na, which is the percent sodium (Na) by weight, and RI, which is the refractive index of the glass.

enter image description here


Length 22:

unique(presidential$n)

The unique() function returns a vector containing the unique values from its input vector in the order in which they appear in the input. The presidential dataset ships with the ggplot2 package (27). (Thanks to Jemus42 for correcting that!) Its description:

The names of each president, the start and end date of their term, and their party of 10 US presidents from Eisenhower to Bush W.

presidential is a data frame, and data frames contain columns just as lists contain items. Columns are referenced by name using $. This particular dataset has a column called name, containing the name of the president. But wait, we only specified n! Actually, this is yet another example of partial matching (13, 16), so n is totally legit.

Submitting this has an interesting result:

[1] "Eisenhower"  "Kennedy"  "Johson"   "Nixon"  "Ford"  "Carter"
[7] "Reagan"      "Bush"     "Clinton"

Notice how Lyndon B. Johnson's name is spelled... Oops.

(Note: It has come to my attention, over a year after posting this, that the Johnson typo has been fixed. RIP humor.)


Length 21:

integrate(dexp,0,Inf)

R has a built-in function for adaptive quadrature of functions of single variable over a finite or infinite interval. In R, infinity is specified as Inf for +infinity and -Inf for -infinity. The dexp() function is the probability distribution function for the exponential distribution. Since the support of the exponential distribution is [0, +infinity) and probability distributions integrate to 1, we would expect the result to be 1. Behold, an expected result!

1 with absolute error < 5.7e-05

Length 20:

deriv(~cos(x^3),"x")

R can do symbolic derivatives! This returns:

expression({
    .expr1 <- x^3
    .value <- cos(.expr1)
    .grad <- array(0, c(length(.value), 1L), list(NULL, c("x")))
    .grad[, "x"] <- -(sin(.expr1) * (3 * x^2))
    attr(.value, "gradient") <- .grad
    .value
})

Looking through that you can see how it parses the function and uses the chain rule. Everything a function who took first year calculus should be able to do! The first argument to the deriv() function is an R expression (which is an actual R type) in terms of some variable, in this case x. The second argument is the name of the variable with respect to which the derivative is taken, here "x".

Want to see something really neat? Assign the above to a variable, say dx. Define a variable x as a numeric vector. Then submit eval(dx). R evaluates the derivative at x!


Length 19:

c(matrix(1,3,3),"a")

In R, c(), short for "combine" or "concatenate," creates a vector from its arguments. The elements of vectors must be of the same type and all have length 1. But instead of getting mad at you about it, R will flatten an element with structure, in this case a matrix, and cast everything to the same type.

If the arguments to c() contain only a single type, no type casting occurs, e.g. if all arguments are logicals (TRUE and FALSE), the vector will be all logicals. If it contains logicals and numbers, it will be all numbers. If it contains character and anything, it will be all character. So our snippet gives us this:

> c(matrix(1,3,3),"a")
[1] "1" "1" "1" "1" "1" "1" "1" "1" "1" "a"

Note that the 3 by 3 matrix was flattened and the addition of "a" made everything into characters.


Length 18:

(1-1/3-1/3-1/3)==0

A lesson in machine precision. This returns FALSE.


Length 17:

example(readline)

The example() function will give you an example of how to use any built-in function. If you need to find out how to use readline(), R has a smug answer for you.

> example(readline)

readln> fun <- function() {
readln+   ANSWER <- readline("Are you a satisfied R user? ")
readln+   ## a better version would check the answer less cursorily, and
readln+   ## perhaps re-prompt
readln+   if (substr(ANSWER, 1, 1) == "n")
readln+     cat("This is impossible.  YOU LIED!\n")
readln+   else
readln+     cat("I knew it.\n")
readln+ }

readln> if(interactive()) fun()
Are you a satisfied R user?

Way to be modest, R.


Length 16:

acf(lh,t="part")

The acf() function returns the autocorrelation function for a time series. lh is a dataset that ships with R. Its description:

A regular time series giving the luteinzing hormone in blood samples at 10 mins intervals from a human female, 48 samples.

In this example, partial matching is being used twice: once with the function parameter and once with the string value passed to the parameter. The full parameter name is type and the recognized values are "correlation", "covariance", and "partial". Only enough of the string has to be provided to identify it uniquely, so we can use "part" for "partial", which gives us the partial autocorrelation function (PACF).

enter image description here


Length 15:

p3d(bunny,p=99)

Again we see the infamous bunny (11). The onion package gives us an even nicer way to view the most useful dataset ever, using the 3D plotting function p3d(). This calls the base graphics function persp() in the background, which takes a rotational argument phi. Using partial matching of parameter names (13), we can specify just p= in place of phi=.

enter image description here


Length 14:

stats:::rgamma

R is open source but you don't have to be a wizard to view the source code; you can just type the package name and the function whose code you want to view separated by three colons (:::). This gives you the code that defines the rgamma() function, which generates random deviates from the gamma distribution. Submitting this gives:

function (n, shape, rate = 1, scale = 1/rate)
{
    if (!missing(rate) && !missing(scale)) {
        if (abs(rate * scale - 1) < 1e-15)
            warning("specify 'rate' or 'scale' but not both")
        else stop("specify 'rate' or 'scale' but not both")
    }
    .External(C_rgamma, n, shape, scale)
}
<bytecode: 0x00000000098cd168>
<environment: namespace:stats>

Note that it uses a function .External(). This calls functions written in other languages, typically C and Fortran, the languages which comprise much of the foundation of R. Locating that source code does take a bit of wizardry. Edit: @Vlo pointed out that mere mortals can indeed view underlying C code invoked with .Internal() and .Primitive() using the pryr package. Thanks, @Vlo!


Length 13:

sample(9,s=4)

This doesn't look like much, but it exemplifies a powerful concept in R: partial matching of function parameters. The named parameters in the sample() function are size, replace, and prob, but you only need to provide enough letters of the named parameter to identify it uniquely. Thus for sample(), you can use s= instead of size= since no other parameter names begin with the letter "s". The code here selects a random sample of size 4 from the integers 1 to 9.


Length 12:

LETTERS[-pi]

There's a built-in vector called LETTERS which contains all uppercase English letters ordered alphabetically. Unlike many other languages, you can index a vector using a floating point number. Nothing too exciting happens; R just takes the integer portion. Using - preceding the index of a vector removes the element with that index from the vector. pi is a built-in constant containing--you guessed it--the irrational number π. So this removes element 3 from the vector and returns "A" through "Z" omitting "C".


Length 11:

plot(bunny)

In the onion package, there's a dataset called bunny. Plotting it gives you what may be the most useful graphic of all time:

enter image description here


Length 10:

????sample

Say you're REALLY confused about the sample() function and you desperately need help. Rather than the usual ?sample to pull up the R manual page, you pound out four question marks. R hears your plight and attempts to help...

Contacting Delphi...the oracle is unavailable.
We apologize for any inconvenience.

Alas.


Length 9:

isTRUE(1)

At first this looks to defy the convention in the rest of the R base package to separate is and the following word in the function name with a .. However, that only applies to a logical test of whether the argument is of a certain type, as below (8). In this case, we're testing whether it is TRUE, which is not a type. This uses a strict definition of TRUE, i.e. 1 is not "true" in the usual sense. isTRUE(1) returns FALSE.


Length 8:

is.na(8)

Unlike most other programming languages, . is a valid character in function and variable names. It does not denote any sort of method or heirarchy; it's just part of the name. The is.na() function checks whether its argument evaluates to NA (missing) and returns TRUE or FALSE.


Length 7:

stop(7)

This issues an error with the input as the error message. If called inside of a function, the function execution will stop. But calling it outside of a function won't stop the script. In this case, the output is Error: 7.


Length 6:

x < -1

While this may seem trivial, it displays a major criticism of the assignment operator <-: namely, the meaning changes depending on the placement of spaces. As mentioned, x <- 1 assigns 1 to x. Separating < and - with a single space as above changes it to a logical test of whether x is less than -1. For that reason, many prefer = for assignment.


Length 5:

x<<-1

Similar to <- except <<- always assigns the variable to global scope regardless of the current scope.


Length 4:

x<-1

R uses <- to assign variables in the current scope. This snippet assigns the value 1 to x.


Length 3:

!0i

The ! operator is R for "not," and 0i is the complex number 0+0i, AKA 0 in the complex plane. Submitting this statement returns TRUE since 0 is false.


Length 2:

NA

This returns the special R value NA, which stands for "not available," denoting a missing value.


Length 1:

T

This returns TRUE. In R, T and F are synonyms for the boolean values TRUE and FALSE, respectively.

Alex A.

Posted 2015-01-19T12:36:59.320

Reputation: 23 761

Yay R "!"(T) ! – Vlo – 2015-01-20T21:18:23.620

@Vlo: "!"(T) evaluates to FALSE. However, the statement "Yay R" is never false. ;) – Alex A. – 2015-01-20T21:34:05.483

How do I upvote more for more entries???? "Locating that source code does take a bit of wizardry" is trivial for .Internal and .Primitive -> pryr::show_c_source(.Primitive("sum")) – Vlo – 2015-01-23T20:31:28.297

@Vlo: I hadn't heard of the pryr package. Very cool! Thanks for pointing that out. I'm glad you like the entries so far, thanks for the support. :) – Alex A. – 2015-01-23T21:05:41.697

Hadley keeps on bringing us the goods. I also didn't know that you can subset with decimal values. – Vlo – 2015-01-23T21:16:27.363

@Vlo: Hadley is the man! – Alex A. – 2015-01-23T21:24:02.597

Regarding 11: Doesn't work for me :/ http://dump.jemu.name/LWYXc.png

– Jemus42 – 2016-02-18T03:37:24.933

Regarding 14: Simply entering rgamma (no parentheses!) with stats loaded (default) works, too, no ::: is needed – which I thought was only used to access non-exported functions anyway, or am I missing something? (I'm still fairly new to R) – Jemus42 – 2016-02-18T03:41:26.317

2@Jemus42 Ah, looks like you need to do data(bunny) first. – Alex A. – 2016-02-18T03:53:08.283

@Jemus42 I used stats:::rgamma specifically because it showcased the triple colon and didn't require an external package. (For a package that isn't loaded, you'd need :::.) – Alex A. – 2016-02-18T03:55:20.917

@AlexA. Thanks, works! Should have thought of that m) Also: Regarding 22: presidential is not in base, it's in ggplot2. But ggplot2 is practically base for the new kids :) – Jemus42 – 2016-02-18T03:55:34.243

@Jemus42 Oh, good catch about presidential. I always have ggplot2 loaded anyway. :D Looks like they fixed the Johnson typo since I made this post, which is good in a practical sense but sad in a comedic sense. – Alex A. – 2016-02-18T03:58:45.330

Why infamous? It looks so nice – Luis Mendo – 2016-06-04T11:48:46.830

75

Brainfuck

Factoid: Brainfuck (Also known as brainf*ck) was a experimental esoteric language for creating the smallest turing-complete language interpreter ever, created by Urban Müller, and is currently the most famous language of its kind. It has only eight commands, is easy to learn, but hard to use.

Brainf*ck has a tape base memory with 30000 cells and a a movable pointer, and can be visualized like this:

0 0 0 0 0 0
    ^

With the ^ character representing the pointer, and the 0's representing the values for each cell.

Brainfuck has eight instructions:

Instruction  C Equivalent              Description
+            mem[ptr]++;               Add one to the value under the cell
-            mem[ptr]--;               Subtract one from the value under the cell
>            ptr++;                    Go on cell to the right
<            ptr--;                    Go on cell to the left
,            mem[ptr] = getchar();     Read a ASCII character from input and put the result in the value under the cell
.            putchar(mem[ptr]);        Write a ASCII character to the output using the value under the cell
[            while (mem[ptr]) {        Start a while loop: Continue to matching ']' when value under the cell is 0
]            }                         End a while loop: Go back to matching '[' when value under the cell is NOT 0

Brainfuck to C:

#include <stdlib.h>

int main(void) {
    unsigned char* mem = calloc(30000, sizeof(unsigned char));
    unsigned int ptr = 0;

    // Put your brainfuck code here, converted to the matching expressions under "C equivalent"

    return 0;
}

Length 1 Snippet

Read one character and put it in the current cell.

,

Memory (with input: abc)

0 0 97 0 0 0
    ^

Length 2 Snippet

Add one to the current cell, and shift the pointer to the right.

+>

Memory

0 0 1 0 0 0
      ^

Length 3 Snippet

Remove one from the current cell until it is zero; Set the current cell to zero

[-]

Possible memory:

Memory: (Before)

0 0 100 0 0 0
    ^

Memory: (After)

0 0 0 0 0 0
    ^

Length 4 Snippet

Comments: In brainfuck, everything not a instruction is ignored. For that reason the following program is a totally valid (but empty) brainfuck program:

Hey!

Length 5 Snippet

A simple cat program (Write input to output)

,[.,]

Thanks to tomsmede for his comment

Length 6 Snippet

Move the value of the current cell to the cell to the right (Assuming the cell to the right is 0, otherwise it would add the value of the current cell to the value of cell to the right):

[>+<-]

In general, people use this code for moving a variable though.

Memory: (Before)

10 0 100 0 0 0
     ^

Memory: (After)

10 0 0 100 0 0
     ^

Length 25 Snippet

Reverse a six character input and print it, followed by every ASCII character (N-1)..1 (where N is the value of the first input character).

,>,>,>,>,>,.<.<.<.<.<[.-]

Length 53 Snippet

main(){i=0;j=0;if(i>=0){if(j<=i)i+=1;i-=1;}return 0;}

This minified C program is also a Brainfuck program in disguise, and vice versa! In fact, they (almost) do the same thing. Here's the Brainfuck code without the "comments" (C code).

><+-

Let me explain the Brainfuck code (and C code). As you can see, it uses two cells (i and j). It increments the first cell (increment i by 1). Then it decrements the same cell (decrement i by 1).

This is just a silly example of some source code being able to be compiled as two different languages and run (practically) the same.

YoYoYonnY

Posted 2015-01-19T12:36:59.320

Reputation: 1 173

2,[.,] -- 5 characters, cat program – tomsmeding – 2015-01-19T17:32:42.380

13This may be the best "Brainfuck 101" I've ever seen. – hoosierEE – 2015-01-22T15:10:16.740

length 6: that would put the sum in the right cell, and zero the left one. Not move, right? – Filip Haglund – 2015-02-15T13:03:36.320

Added a dummy variable to length 6 to better explain the concept. The program will in fact add cell #3 to cell #4 and make cell #3 0. – YoYoYonnY – 2015-02-17T06:56:45.430

58 votes -- could you update? :) – Conor O'Brien – 2016-04-28T02:10:50.383

@Cᴏɴᴏʀ O'Bʀɪᴇɴ I will see what I can do when I get my hands on a computer! – YoYoYonnY – 2016-05-15T00:09:32.950

65

C++

With its preprocessor, templates, lambdas, type traits and countless other complex features that no one can ever hope to understand in its entirety, C++ is rediscovered by each new generation of its standard. By exploiting its numerous ways to do things at compile time, one can write zero overhead abstractions like a library that allows physical units being attached to numeric datatypes in order to check their soundness at compile time (e.g. you can not assign the outcome of kg*m to N)

Length 1

#

Usually introducing a preprocessor statement, # can stand on a line on its own. It essentially means nothing and seems to be so unknown that most syntax highlighters I see don't know it.

Length 2

%:

Of course not everyone has a # key, so C++ is (well, it really inherited it from ancient C) generous to allow you to write it with this alternative token (aka digraph)

Length 3

??=

This is a historical course on C++. These days not necessarily valid anymore, though implementations can support them, are trigraphs. This sequence is translated into # on those systems that support it, but to not interfere with raw string literals, it is not allowed within those. Implementations may chose to drop support alltogether.

Length 4

auto

Is one of the newer (since C++11) inventions to make working with generic code easy. It is for deducing the type of an expression, and since C++14 it can even be used for deducing lambda parameters and the return type of functions.

Length 5

 catch

Is a keyword that is also known from many other languages, present in C++, but the good idiomatic C++ programmer does almost never use it. With its constructors and destructors idiomatic C++ uses a principle widely called RAII (Resource Acquisition is Initialization) or how I like to sometimes call it more appropriately: SBRM (Scope Bound Resource Management). Due to classes like smart pointers, one can tie the lifetime of dynamically allocated resources (that is not only memory!) to other objects. When those go out of scope (e.g. by a thrown exception), these objects automatically clean up resources. This allows for exception safe and easy to use code that doesn't need to use catch.

Length 6

[](){}

[]{}()

As stefan mentioned in the comments, you can use []{} as the shortest lambda object, thus this is the shortest form to call a lambda. The following text is for the old version:

is probably the shortest form of a lambda. Lambdas in C++ are objects (of implementation defined type) that are able to capture part of the scope they are created in (the [] syntax controls this), and are callable (the () syntax controls this). Their code (The {} part) has access to these variables as if they were within their scope. With their optional return type deduction and auto parameter deduction introduced in C++14, they are the tool to use for all the standard library algorithms that expect a callable (e.g. the third std::sort parameter).

Length 7

virtual

Is the keyword to start using runtime polymorphism in C++, one of the basic blocks of object oriented programming. This follows the "don't pay for what you don't use" principle, wheras in other languages all functions are virtual by default. Being a multi paradigm language, it might be a surprise for people thinking "C++ is object oriented" to see programs or libraries that make almost no use of this keyword, e.g. because they follow the generic programming principle.

Length 8

override

Working together with the virtual keyword, override is one of the later additions to C++ to make the compiler do more work for you. By using it, you express the intention of overriding a virtual function in the base class, and the compiler will error out if you did a mistake and that class doesn't have the specified function. In general it is considered good style if your code expresses the intention, rather than fiddle with bits.

Length 9

constexpr

Being also a later addition to C++, constexpr allows the programmer to express for functions or variables, that they are known at compile time and should be computable at compile time. This allows these functions to be used in contexts that need compile time expressions (e.g. as template parameters or array sizes). Many standard library functions (if possible) are already constexpr so they can be used here.

Length 10

for(i:c){}

Is a complete loop over a container, or container like construct that supports std::begin and std::end to get iterators (that includes C style arrays). It is basically equivalent to for(auto __i = std::begin(c); __i != std::end(c); ++__i){ auto& i = *__i; }. This allows for easy looping in generic code.

Length 11

void f()&&;

Is a new way to declare member functions and the properties on the object they can be called on. In previous versions of C++ we only had the ability to chose void f() const; to tell the compiler to be able to call the function on const objects (thus without the const you can not call them on non-const objects). The same way we now have the && syntax for r-value references being used to be able to call those functions on rvalues.

Length 12

int main(){}

This is probably the shortest complete program that you can compile link and run. It will do nothing and return 0. This return is one of the many special cases you can encounter in C++. Normally returning nothing is undefined behaviour, but for the entry point function main, returning nothing means returning 0.

Length 13

auto f()->int

is a rather new way to declare the return type of a function. Normally you would not do this if you already know the type, but there are plenty of situations in generic programming where the type depends on template parameters and the variables you use. Doing it this way allows for a somewhat easier access to these parameters as in template<class T> auto f( const T& t ) -> decltype(t.foo()) instead of template<class T> decltype(std::declval<T>().foo()) g( const T& t ) { return t.foo(); }

PlasmaHH

Posted 2015-01-19T12:36:59.320

Reputation: 1 084

2I would suggest using ; as an alternate 1-char snippet, because it's not a preprocessor macro and the fact that you can have a 1-character statement in C++ at all seems baffling. – Joe Z. – 2015-01-24T05:57:24.077

1[](){} isn't the shortest form of a lambda: As the list of parameters is empty, it may be omitted. Hence []{} is the shortest lambda. Trivially, []{}() is the shortest execution of a lambda ;-) http://ideone.com/k8fAvs – stefan – 2015-01-28T12:01:29.277

@stefan: indeed, I always forget it since it doesn't look function like then ;) I added it to the answer. – PlasmaHH – 2015-01-28T13:11:44.620

@PlasmaHH I absolutely hate it because indeed it doesn't look like a function.. ;-) – stefan – 2015-01-28T14:20:01.763

59

Regex

Length 2 snippet

[]

JavaScript: An empty character class that doesn't match anything.

PCRE, Java, Python re, Ruby (tested on version 2.0): Syntax error.

Length 1 snippet

.

., called dot-all, is available in all flavors I had a chance to look at.

What does it match?

I̧n͟ g̨͜e҉̡͞n̵͢e͜͝r̷͝a͘l̢҉,̡͟ ̴̕̕.̸̴̢̛́ ̸̡̢m͞ąt̴̨c͞h̛e͢͡s̶͘ ͘a҉n̛͜͠ỳ̸ ͢c̵̡hár͘͝a̕͢ćt͘͠e͏̀͠r̷̀ ̴̕͢ex͝͞͞c҉ep̀t̛ ̕f̴҉o͟͜r̴͢ ͞n͏ę͟w̢̕͜ ͡l͝i̸̧n͢͡e̶.͟

Java Pattern: In default mode, dot-all matches any code point, except for these 5 code points \r\n\u0085\u2028\u2029. With UNIX_LINES mode on (but without DOTALL), dot-all matches any code point, except for \n. With DOTALL mode on, dot-all matches any code point. From Java 5, Pattern operates on code point, so astral characters are matched by dot-all.

Python re (tested on 2.7.8 and 3.2.5, may be different on 3.3+): In default mode, dot-all matches any UTF-16 code unit (0000 to FFFF inclusive), except for \n. re.DOTALL lifts the exception and makes . matches any UTF-16 code unit. In these versions, re operates on UTF-16 code units, so . only manages to match one code unit of characters in astral plane.

.NET: Same as Python. The dot-all mode in .NET is called Singleline.

JavaScript (C++11 <regex>): In default mode, dot-all matches any UTF-16 code unit, except for these 4 code points \n\r\u2028\u2029. With s flag on, dot-all matches any UTF-16 code unit. JavaScript also operates on UTF-16 code units.

PCRE: Depending on build option, dot-all can exclude \r, \n or \r\n, or all 3 CR LF sequences, or any Unicode newline sequence in default mode. In default mode, the engine operates on code unit (can be 8, 16, or 32-bit code unit), so dot-all matches any code unit, except for the newline sequences. In UTF mode, the engine operates on code point, so dot-all matches any code point except for newline sequences. The dot-all mode is called PCRE_DOTALL.

PHP (tested on ideone): PCRE, compiled as UTF-8 library and \n is the only newline sequence by default. Dot-all mode is accessible via s flag.

Postgres: In default mode, dot-all matches any code point without exception.

Ruby (tested on version 2.0.0): In default mode, . matches any code point except for \n. Dot-all mode is accessible via m flag (!).

s flag is used to indicate Windows-31J encoding in Ruby.


Factoid

Ŗ͞e̡͟҉ǵ͟͢e̴̢͘͡x̡́͞ ̛̀҉҉̢c҉̷̨a̸̛͞n҉̛͠ ̷̸̀p̴͠͡҉̵ą̧͜͢r̸̸̷̢͝s̢̀͡e̷̷̷͘͞ ̨̧̀H̨̧͜͜T̷͞M̷̛͜L͢.̴̡́ Repeat after me. R̶̶̢̧̰̞̲̻̮̳̦̥ͭͯ́̓̎͂̈ͯͤ̇͊͊͟ĕ̱̹̩̪͈͈͍̗͎̝͚̽̈́ͨ̐̽ͪͮ̍͂͐ͮͧ̔̏̓ͣ̀ĝ̵̢̢̖̤̜̭͔͊͒ͦ͛ͤ͗ͬͧͪ̾͘͟eͦ̄ͭ̑̾҉̨̨̝̬̹̘̭͔͟͢x̣̻͓̠͈͕̥̜͚̱̝̫͚̳̾̍ͦ̑̈́̋̌̉̎͊ͮ͗̄̆̒́̚̚ͅ ̸̦͈̥̬̺͇͂ͧͧ̃͐̎ͮ̌ͤ̈́̒̆ͣ̈́̏̔͊̐̀ç̨̬̪̳̦͎̖͕̦͔ͨ̃̿̓̈́ͅȁ̸̳̺̠̭ͮ̎̓̐͘̕͜͡ņ̨̫͔͍̬̤̘͎͚̣̟̦͍̜ͭͭ̈́ͦ̈́̽͗ͥ̑͝͡ ̸̛̖̝̻̻͎̍̄ͭ̓ͨ̋͋̈́͗̌̇ͤ͋ͬ͘pͪ̒̍ͫͤͭ͊ͮ̇̿̆̐̄̎͌̚͏̧͏͇̼͚̰͓̲͕̰̖̘̟̞̺̲ḁ̛͇̫̻̉̊ͣͭͤ̇ͨ́͘͠rͦ̂̈́̆͑͊ͣ̊ͮ̉̉͆ͧ̒͛̐̋̚͏̴̭̫̞̯̘̖͍̼̖̜̞̖̩͕̹̻̮̗͜͡͞ͅs̟͈̺͖̦̟̙̦͖̤ͬ̋͌̄͂ͩ̓̐̔̓͌̾̀̈͊̊ͤ̀̚eͫ̐͒̽ͯͫͨ͏̨̡̦̤̙͍̙̪̝̮̤͎̭̖̪̻͙͍͖͉̀́ ͉̭̫̰͔̝͓̼̮͚̻͎͎͉̐͗͗͊̇ͣ͒͗͑̆͐̎̐̀ͬ͛ͮ͝H̢̥͕̼͓̫͙̺̼̮ͣͦ̍ͨ͒̔̌T̪̲̦̻̦͖̞̤͒̑ͭ̐̑̃ͭͣ͐̎̒̉͊̀͜͜M̞̪͇͕̩͉͗ͧ̌ͯ͋͂̉̍ͭ̓̇̐̌͜͠Ĺ̷̨̳̘̯͚͓͛͌ͭ̉̍.ͯ͆̊̌ͯ̇̓̏͐ͪ̋̈́͑̕҉̷̠̰̼̤̲̀́

n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳

Posted 2015-01-19T12:36:59.320

Reputation: 5 683

36I feel bad for anyone who doesn't get the factoid's reference. – Robobenklein – 2015-01-20T14:53:15.643

For length 2 in JavaScript, you might want to mention explicitly that it actually fails to match anything, as opposed to matching an empty string. – Martin Ender – 2015-01-20T15:21:06.163

@MartinBüttner: Will change the wording on the next revision. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-01-20T15:40:36.500

6@robobenklein I know a secret medicine for your pain: Just enlighten us! – flawr – 2015-01-20T15:59:51.923

24

@flawr For those that don't know the famous question: the first answer at http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags is what you're looking for.

– Robobenklein – 2015-01-20T16:07:02.960

1You can read the Zalgo'ed text, but don't take them too seriously in both directions. It is plain wrong to follow the way of Zalgo blindly, but the Zalgo text is not wrong all the time. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-01-20T17:08:57.177

12@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, aren't you going to use all those votes to show us how to parse HTML? – mbomb007 – 2015-01-23T15:49:35.613

@mbomb007: The number of votes is no where near enough. And I'm not an expert on Perl, which is the only language that is capable of doing so. However, you can take a look at this HTML parser (?) written in Perl regex by tchrist on StackOverflow.

– n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-01-23T16:01:32.487

@n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳, I was making a joke. :D – mbomb007 – 2015-01-23T16:19:21.097

If I make an HTML parser with regex, what will you give me? – Ismael Miguel – 2015-01-23T18:41:22.133

1@IsmaelMiguel: Feel free to do so. I'll give you some Internet cookie. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-01-23T18:47:23.817

Meh, not enough reward. I get cookies on every website I go! – Ismael Miguel – 2015-01-23T18:57:17.967

@IsmaelMiguel: tchrist has demonstrated that it is possible, so I don't know what I should reward you for. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-01-23T19:14:25.143

He only demonstrated that it is possible, not that it is an actual usable tool. Like a state machine. – Ismael Miguel – 2015-01-23T19:18:51.810

@IsmaelMiguel: If you think you are up to the task, then feel free to do so. When you are done, publish your work, blog about your experience and let people try out your tool. I'm not sure why you are asking me for reward. My stance is that there is time and place for everything, and I choose the tool which best fit the task. I'm not denying the possibility in anyway, if that's what you are getting from my post. – n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳ – 2015-01-23T19:41:13.623

Probably I'm getting the wrong impression. Sorry about it. But it definetively can be done. You just need some clever trick. – Ismael Miguel – 2015-01-23T19:58:11.307

You have 55 updoots now, will you add new snippets? – TuxCrafting – 2016-11-11T18:41:10.753

57

J

PS: Snippets now linked to tryJ.tk letting you play around with them running in JavaScript in your browser, without installing J.

PPS: I swapped order; this makes more sense for people joining in, and for future reference.

PPS: I think, due to time constraints, I will add one snippet a day

factoid:

J is a descendant of APL (see here for the family history) minus the funny character set.

Length 1 snippet

_

J uses _ both as infinity and as negative indicator, when attached to number literals (opposed to the verb -).

Length 2 snippet

a.

a. is called Alphabet, containing all 1 byte characters. As such J does not contain functions like atoi, since they are simple look-ups in the alphabet: a. i. 'z' =122

Length 3 snippet

i.9

i. is for Integers, when used monadically (ie. only one argument, the right one, usually called y). When used dyadically it serves as index of, as in the example above.

Length 4 snippet

!!6x

J supports arbitrary precision integer and rational numbers. This calculates the factorial of the factorial of 6 (a 1747 digit number).

Length 5 snippet

^.^:_ 

A dense one... First, verbs (as J calls functions) are organized by theme. All ^ verbs are tied to exponentiation. ^ for exponentiation (and exp when used monadically, ^. for logarithms. ^: is a special one, the Power conjunction (a higher order function), which applies a function a number of times. When right the argument is infinity (_) it executes its left argument (in the example ^.) on its own output till it converges. In effect, ^.^:_ is a verb solving x = ln(x) when applied to any argument but 1, yielding 0.318132j1.33724.

Length 6 snippet

^0j1p1

or equivalently

^o.0j1

Euler's Identity in J. As cited above, ^ is exp(). Apart from arbitrary precision integers and rationals, it also supports powers of pi and complex numbers, and combinations hereof as literals. 0j1p1 means (0 + j) * pi ^ 1.

Length 7 snippet

+/&.:*:

A verb taking the 2-norm of any vector. This demonstrates 2 things:

  • the Insert adverb turns the Add verb + into Sum by inserting it between each element of its argument. Hence (0+1+2+3) = +/ i.4 .

  • The conjunction Under when used as v &.: u y is equivalent to vi u v y, where vi is the obverse (generally the inverse).

Yes, J knows about functional inverses. Combining these makes the verb in the snippet equivalent to %: @: (+/) @: *:, or sqrt(sum(y.^2)) in Matlab for instance.

Length 8 snippet

$#:I.@:,

A fork is composed of 3 verbs without any reference to arguments. This allows what in J is called tacit (point-free) programming. A fork f g h, in the monadic case (as in this example) is equivalent to (f y) g (h y). As forks, multidimensional arrays are an intrinsic part of J. "Indices" returns the indices of ones in a vector, but does not extend to higher dimensions as such. This example uses Shape, Antibase and I.@:, as the 3 tines of the fork implementing I. for higher dimensional arrays, for instance:

 ($#:I.@:,) 5 = i. 5 5 NB. indices of 5 in i. 5 5

Length 9 snippet

<"1 i.4 6 

Boxed arrays are a data type in J, allowing to combine heterogeneous content (both type and size) into one value. Monadic < boxes it's argument. Rank is a central concept in J, and allows to automatically extend verbs towards arrays of higher dimensions. Both nouns and verbs have a rank.

Noun rank is the number of dimensions of any noun, which the verb $@$ can tell you. For example i. 2 3 4 is an array of rank 3.

Verb rank is the rank onto which a verb will apply itself. Every verb has an intrinsic rank which can be queried with the Basic conjunction. v b. 0 returns 3 numbers for the monadic, dyadic left and dyadic right rank of the verb v.

A verb works on noun cells of rank equal to the verb rank, and replaces results in a noun rank-verb rank frame. A verb's rank can be limited using the Rank conjunction, as is done here, boxing rank 1 cells (rows) instead of working on rank _, ie. boxing the entire array. More info on rank can be found here.

Length 10 snippet

<./ .+~^:_

This snippet is a verb calculating the shortest path over weighted digraph. It introduces minimum (<./) and the Dot conjunction. The dot conjunction is a generalization of the matrix product, which can be written as +/ . * . Generally, u . v is equivalent to u@(v"(1+lv,_)) where lv is the left rank of the verb v. Or in words "u is applied to the result of v on lists of “left argument cells” and the right argument in toto". (See above for ranks)

As such the inner verb <./ .+~ replaces item y(i,j) with the minimum of y(i,k)+y(k,j) for all k.

^:_ iterates this step till convergence.

Example, displaying original and shortest path distances:

(]; <./ .+~^:_ ) wtm=: _6]\0 2 5 _ _ _ _ 0 4 1 3 _ _ _ 0 _ _2 _ _ _ 4 0 _ 5 _ _ _ _1 0 6 _ _ _ _ _ 0

Length 11 snippet

<.@o.10x^99

This snippet introduces special code: Some J code is supported by code specifically written for a certain use case, recognized at parse time, and optimized; either for higher accuracy (as is the case here) or higher performance (see Special combinations)

This phrase gives 99 digits of pi (though shifted 99 decimal places). Special code depends on exact phrasing, what would normally be equivalent is not as precise as the snippet code: <.o.10x^99 looses the extended precision.

Length 12 snippet

($-.1:)($,)]

From time to time, you end up in situations where due to selections made in data, there are singleton dimensions running in the way. This handy utility, called squeeze in Matlab, squeezes out all singleton dimensions. The left tine of the fork ($-.1:) yields all dimensions without the ones, while the middle one ($,) reshapes the raveled array to the dimensions retained. The right tine ] serves just to make this a fork, and references the right argument.

Length 13 snippet

1 :'-u%u d.1'

Newton's Method finds an approximation of a root of a differentiable function. This explicit adverb is to be applied to the function of which the root is sought, and represents one step of the iterative procedure. u is the argument referencing the function, being replaced the moment the adverb is applied. d. is a conjunction deriving functions symbolically, and might here be replaced by D. which does the same numerically (but differs when applied to higher rank functions). The result is a hook subtracting the fork ( u divided by its derivative) from the argument.

For example:

(_2 + *:) (1 :'-u%u d. 1')^:_ ] 1 NB. root of x^2-1; ] is there to avoid combining _ and 1 into an array.

Length 14 snippet

(%-.-*:)t.i.10

First 10 numbers of the Fibonacci series by Taylor expansion of x / (1 - x - x^2). Analyzing the hook %-.-*: gives (y % (-.-*:) y) = (y % ( (1 - y) - *: y).

Length 15 snippet

(#{.+//.)!/~i.9

Another take on Fibonacci series. This time from another angle; starting from Pascale's triangle '!/~i.9' .

/ when used dyadically means Table, applying the verb it's bound to between each cell of it's arguments, yielding a table of the operation between arguments x and y. In this case ! used dyadically, as Combination (or Out of). ~ makes the verb Reflexive, ie. use it's right argument as the left one too.

The adverb /. is an odd one, it applies it's verb along the anti-diagonals of an array (ie. try </.!/~i.5 here )

So this snippet takes the sums on the 9 first anti-diagonals on the Pascal's triangle, which happens to be another occurrence Fibonacci series.

Length 16 snippet

;/@~.,. <"0@#/.~:

Ok, I added a space just to get to 16 :). This snippet demonstrates a fork using Key: listing all items in the argument and their frequencies.

x u/. y applies u to y in chunks where x is unique, or in J : (=x) u@# y, where = is Self-Classify, which generates a boolean array containing 1's in positions where they appear in the nub ~. Here it's applied reflexively, hence executing Tally on each unique item in y, counting the number of appearances.

As most verbs in J keep the nub order (order of appearance of new unique items, opposed to for instance unique in Matlab, which sorts its argument) this can be used for Stiching the items to their frequencies as is done here. ;/@~. is used to make a boxed list of all items.

Note that because the prevasive concept of Rank, this code works for any dimensionality.

Length 17 snippet

*./ @:(#&>)@C.@A.

J supports a few primitives specifically about permutations:

  • Anagram A. Monadically it finds the Anagram index, dyadically, it applies the permutation specified by the anagram index in the left argument to the right argument.
  • Cycle - Permute C. converts between direct and cycle representation of permutations.

This snippet is a verb that takes an anagram index to the left (between 0 and !#y) and right argument y an array to permute. Afterwards, it computes the LCM *./ of the cycle lengths #&>, ie. the period after which you get the original array back:

]n=: (p=:?!9) *./ @:(#&>)@C.@A. i.9 NB. period of a random permutation
p&A.^:n i.9 NB. applies permutation n times.

Length 21

<:@(#/.~)@(i.@#@[,I.)

This little verb comes from the "stats/base" add-on, and is called histogram. It does exactly that, given a list of bin starts, sums all occurrences of data between in the interval ]bn-1,bn] where bn is the start of bin number n.

It exploits Interval Index I. for finding the interval of:

If y has the shape of an item of x , then x I. y is the least non-negative j such that j{x follows y in the ordering, or #x if y follows {:x in the ordering or if x has no items.

Making the totals of each interval is done using key as highlighted in snippet 16.

The snippet linked to on tryj.tk demonstrates the central limit theorem using this histogram:

(bins=:(%~>:@i.)10) ( [ (graph=:(,&":"0 1 '#'#"0 1~])) (histogram=:<:@(#/.~)@(i.@#@[,I.)) ) (+/%#) ?5 200 $ 0

Length 22

=,&(+/)(~:#[)e.&~.~:#]

Fun in J. This implements a mastermind engine, taking a secret array as left argument, and a guess as the right. The values returned are the number of white and black pegs. Taken apart:

NB.   ExactMatch: checks where digits correspond:
ExactMatch =: =

NB.   GoodDigitWrongPlace: Copies non-matched numbers from both arguments (left and right
NB.   pairs of parentheses, and checks them for same elements(e.), after eliminating
NB.   doubles in both (&~.)
GoodDigitWrongPlace =: (~: # [) (e.&~.) (~: # ])

NB.   Piecing the conditions together, after summing the booleans:
mm =: ExactMatch ,&(+/) GoodDigitWrongPlace

To be used like

secret (=,&(+/)(~:#[)e.&~.~:#]) guess

Where secret and guess are any array. It works with any data type actually.

jpjacobs

Posted 2015-01-19T12:36:59.320

Reputation: 3 440

17Well, either you get an unreadable heap of weird symbols, or you get an unreadable heap of ASCII symbols. Pick your poison. – John Dvorak – 2015-01-19T12:57:13.353

16@JanDvorak All languages are unreadable until you learn them. ;-) – Gareth – 2015-01-19T13:10:34.673

5

I used to think long, descriptive names aid code comprehension. Then I was enlightened.

– hoosierEE – 2015-01-22T15:09:33.193

@Gareth But not all are unreadable even after you learned them. Not gonna name any names. – flawr – 2015-04-13T20:27:59.730

45

RPL (Redstone Programming Language) [and Minecraft]

This is a big stretch on whether or not we can consider this a real programming language or not, but we will try anyway. And, as these two "languages" are practically the same, I will combine them, sometimes post snippets in "Minecraft" language (redstone, etc) and sometimes in RPL. Also, since many snippets will be in Minecraft, I will post links to the pictures rather than the pictures themselves to save space. Additionally, all snippets will be of programming concepts in Minecraft, not general redstone (i.e. no redstone doors will appear). Characters will be counted in bytes (in RPL) or as according to this (in Minecraft).

Factoid:

RPL is a programming language by Tossha the Inventor that converts code into Minecraft redstone and command blocks. It can do input and output, loops, integer manipulation, trig functions, roots, and more.

Length 1:

A button (1 byte) is the simplest form of input in Minecraft. It also can start or stop a "program". Similarly, a lever (also 1 byte) is another form of input, and can also be used to both start and stop the program as it has an "on" and "off" state. Something to remember is that Minecraft is literally a 3D programming language, so where the button/lever is place in the program can make a huge difference.

Length 2:

A button attached to a redstone lamp is pretty much your very basic cat program. It takes the input (with a button or lever, either 0 or 1 (off or on)) and outputs it in the form as light from the lamp as either 0 or 1 (off or on).

enter image description here

Length 3:

As seen below, this one of the shortest source-code modifying programs (as you can modify the source at runtime with Minecraft!). Now, this specific one really has no use, but the concept can be combined with others to create some awesome programs (as to come with more upvotes). When run, this program removes its source of input, and makes itself unable to be run again. enter image description here

Length 4

This "snippet" actually shows two concepts: delay, and the NOT gate. Delay is made using certain redstone elements that have a redstone-tick delay. A redstone-tick is equal to one-tenth of a second. Different redstone components have different delays: a torch has a 1rt delay (1 redstone-tick), a comparator has a 1rt delay, a repeater can have a 1, 2, 3, or 4rt delay, depending on how it is set up. In this example, the redstone repeater is set to a 4rt delay.

Next is the NOT gate. The NOT gate takes an input an inverts it. So in this set up, the output will be on if the input is off, and the output will be off if the input is on.

Length 5

The OR gate is very easy to accomplish in Minecraft. Two inputs are connected to the same output. That is it. No funny trickery or anything, it's pretty simple.

enter image description here

Length 6

Here is a tip for compacting your "code". If you know the signal strength of two inputs are small enough to not interfere with the corresponding outputs, you can wire the redstone right nect to each other. In the example below, there is a simple hopper timer, which transfers items back and forth in about 0.5s in each hopper, conncected to comparators that output a signal strength of 1. This means that the two ouputs will not interfere with each other. In the example, the lamps are there for demonstration purposes only and don't count towards the total block count.

enter image description here

GamrCorps

Posted 2015-01-19T12:36:59.320

Reputation: 7 058

I can haz more programs? ;) – ETHproductions – 2015-12-09T16:37:34.983

@ETHproductions,, I am currently in the process of preparing for finals, so I do not have much time at the moment. However, I should have it updated by Friday. – GamrCorps – 2015-12-09T16:47:51.617

That's OK. There's no rush. – ETHproductions – 2015-12-09T16:51:44.453

7You haz 13 upvotes, I can haz 10 moar programs? – Rɪᴋᴇʀ – 2016-03-31T15:33:28.140

4None of your programs are actually written in RPL, so don't pass it off as such. This is purely Minecraft "code". – mbomb007 – 2016-04-20T16:06:13.807

2You have a deficit of 14 programs m8. I'd like to see what you have in mind ;) – Conor O'Brien – 2016-04-21T18:02:22.277

4You haz 21 upvotes, I can haz 15 moar programs? – wizzwizz4 – 2016-04-30T18:28:12.627

1You haz 29 upvotes, I can haz 23 moar programs? – bb010g – 2016-08-09T19:56:35.817

You haz 36 upvotes, I can haz 20 moar programs? – RudolfJelin – 2016-11-05T19:46:08.777

1You haz 37 upvotes, I can haz 31 moar programs? – Erik the Outgolfer – 2016-12-16T17:46:19.290

42

TI-BASIC

[The language varies based on which calculator it is used on, but these will use the TI-84 unless otherwise noted.]

Length 31 snippet

Menu("","1",A,"2",B
Lbl A
Lbl B

This demonstrates the use of menus. The one above is quite useless, as it does nothing, but they can be used to navigate the different part of a program. The first argument is the menu title, followed by pairs of options (the string displayed followed by a 1- or 2-letter label). Here is a more intuitive example:

Menu("CHOOSE VALUE","AREA",A,"CIRCUMFERENCE",C
Lbl A
Disp πR²
Stop
Lbl C
2πR

Lbl can also be used for branching with Goto. Menus have some limitations that make them annoying to use, however: There can only be seven menu items, and each title can be at most fourteen characters, so the whole thing fits on one screen.

Length 29 snippet

Real
√(-16
a+bi
Ans
re^θi
Ans

Real (on by default) places the calculator in real number mode, so calculations involving complex numbers throw a NONREAL ANS error. When put in a+bi mode, the calculator displays answers as complex numbers if applicable, so the second example returns 4i. re^θi mode uses polar instead of rectangular coordinates, so it outputs 4e^(1.570796327i).

Length 23 snippet

If A≥9
Then
1→X
7→Y
End

This is just a simple conditional, although there can be an Else statement. Then and End are not required if it is just one statement.

Length 21 snippet

(-B+√(B²-4AC))/(2A)→X

Everyone's favorite, the quadratic formula. Stores the first solution to a quadratic equation as X, assuming a, b, and c are stored in their respective variables, as in ax2 + bx + c.

Length 20 snippet

Shade(|X/2|-3,5-X²,0

This shades the intersection of the two functions, with several optional parameters: minimum and maximum values of x and direction of and distance between the shading lines.

Length 18 snippet

LinReg(ax+b) L1,L2

Here we calculate the linear regression equation, or the linear equation that best matches a group of points, with the x-values stored as a list in L1 and the y-values in L2. There are many other regression options available, including quadratic, cubic, and exponential.

Length 17 snippet

dbd(1.2711,1.2115

This calculates the number of days between two dates, in this case January 27, 2011, the day this site started, and January 21, 2015, the day this was written. (That's 1455 days for the lazy.) The way to encode dates is a little strange: either DDMM.YY or MM.DDYY, leading zeroes optional.

Length 16 snippet

For(A,0,5
Disp A

This shows two parts of the programming side of the language. The first is your typical for loop, similar to for(var A=0;a<5;a++) in other languages. (You should also use the End command to break out of the loop.) The second is self-explanatory: it displays A, in this case 5 times because of the loop.

Length 15 snippet

Y1=|X³-4|
Y2=3X

Here are two examples of a well-known feature of graphing calculators: graphing equations. You can have 10 different equations graphed on the same plane, and there are many useful commands to find intersections, maxima, values of x, etc. Those equations look like this when graphed on a standard window:

Graph

Length 14 snippet

[[1,2][34,5]]T

The brackets are used to make matrices, and the T transposes the matrix:

[[1 34]
 [2 5]]

Length 13 snippet

dayOfWk(9,1,6

This finds the day of the week of January 6, 9 AD. The output is a number where 1 is Sunday, 2 is Monday, and so on. This particular date was a Tuesday, so the output is 3.

Length 12 snippet

Circle(1,3,5

The first of the basic drawing tools, this draws a circle on the graph with a center at (1,3) and a radius of 5.

Length 11 snippet

randInt(0,8

This generates a (pseudo-)random integer between 0 and 8 inclusive. There is an optional third argument that tells how many integers to generate. There are several other random functions, including ones for normal and binomial distributions, one for a random matrix, and one for a randomly ordered list with no repetitions. randInt can be seeded by storing a number as rand: 2→rand.

Length 10 snippet

4>5 or 2≠7

Here we have TI-BASIC's (in)equality and logic operators. The inequality statements evaluate first to 0 or 1, and or returns true if either side is true, so this displays 1.

Length 9 snippet

.656▶F◀▶D

This can convert from decimal to fraction and vice versa, which is very useful. There are also dedicated ▶Frac and ▶Dec functions that only go one way. Prints 82/125 in this case.

Length 8 snippet

lcm(14,6

This prints the least common multiple of 14 and 6, which is 42.

Length 7 snippet

getDate

Pretty self-explanatory, just prints the current system date as a list, in this case {2015 1 19}.

Length 6 snippet

√({4,9

Arrays (or lists) are surrounded by braces and separated by commas. This is similar to the map function of many languages, where it iterates through each element of the list and applies the operation outside the braces to it, in this case square root, so the result is {2 3}. Note that closing parentheses are optional, so they will be omitted from now on.

Length 5 snippet

4iii6

We've got a couple of cool things going on here. First, the real parts, 4 and 6 are multiplied, and then the imaginary parts are multiplied: i^3, or -i. These multiplied give -24i. This showcases funky-looking juxtaposition multiplication and TI-BASIC's handling of imaginary numbers.

Length 4 snippet

8°5′

This is 8 degrees, 5 arcminutes, which is converted to degrees as 8.0333...

Length 3 snippet

8→T

This shows how numbers can be stored as variables, which is somewhat unusual because the number goes first, followed by the store arrow, then the variable name. As mentioned in the factoid, θ (theta) can also be used as a variable, and variables can only be one uppercase letter.

Length 2 snippet

4M

Similarly to Mathematica, you can multiply with juxtaposition, no * necessary. All variables are initialized to 0 by default, so this will output 0 unless you have stored something else to that variable (see snippet 3).

Length 1 snippet

e

This is the constant for Euler's number, which displays as 2.718281828.

Factoid

Variables can only store certain datatypes. For example, AZ (and θ) store numerical values, str0str9 store strings, and [A][J] store matrices (2-dimensional arrays).

NinjaBearMonkey

Posted 2015-01-19T12:36:59.320

Reputation: 9 925

By the way, the lower case n (not n) can also be used as a variable. – Ypnypn – 2015-01-21T15:28:15.640

Interesting. I've never used that variable. – NinjaBearMonkey – 2015-01-21T16:40:29.583

3One can argue about str0 being 1 character or being 4. All instructions in TI-BASIC are 1 character long. – Ismael Miguel – 2015-01-23T18:51:50.257

@IsmaelMiguel I thought about that, but they are 1 or 2 bytes, and I decided to count characters normally. – NinjaBearMonkey – 2015-01-23T19:27:46.087

1I respect your decision. It helps a lot in this case. I really enjoyed programming on my oldie TI-83. (I've even designed a paint program in it!) – Ismael Miguel – 2015-01-23T19:31:46.833

@Ypnypn Is there an Unicode codepoint for n (not n)? – jimmy23013 – 2015-02-21T15:19:45.370

Two small things: First, I enjoy how you focus more on the math aspect of TI-BASIC than the code golf aspect; second, your length 16 snippet actually needs the End or the interpreter will not loop back. – lirtosiast – 2015-06-23T01:12:01.677

41

GNU Sed

I am self-imposing a more restrictive requirement - all snippets will be complete sed programs.

Factoid

sed is a turing-complete language. Here is a proof.

Length 0 Snippet

I don't think a length 0 snippet is strictly required, but since it actually does something in sed, here it is:

Sed is the "Stream EDitor", i.e. it reads the stream (line-by-line) from STDIN, edits, then outputs to STDOUT. The zero-length sed program simply copies STDIN to STDOUT. Thus the cat utility may be emulated by sed. The following are equivalent:

cat a.txt b.txt > c.txt

and

sed '' a.txt b.txt > c.txt

Length 1 Snippet

=

This sed program prints the line number of each line to STDOUT. This is approximately equivalent to:

nl

or

cat -n

although the sed version puts the line number on its own line.

Length 2 Snippet

5q

Copies STDIN to STOUT and quits after line 5. This is equivalent to:

head -n5

You might be starting to see a bit of a pattern here - sed can be used to emulate many of the standard core-utils tools.

Length 3 Snippet

iHi

inserts "Hi\n" before every line. Meh.

Length 4 Snippet

/a/d

A lot of sed's power is in its regex capability. This program causes all lines matching the regex a to be deleted from the stream. All other lines will still be output to STDOUT. This is equivalent to:

grep -v "a"

Length 5 Snippet

:l;bl

This is an infinite loop. We all love CPU-hogging infinite loops. Defines a label l, then branches (jumps) to it. Ad infinitum.

Length 7 Snippet

s/a/A/g

By default, sed applies s commands such that it will match just the first occurrence on each line. If you need it to match (and substitute) every occurrence on a line, then the g flag at the end of the s command will do this.

Length 8 Snippet

y/01/10/

The little used y command is similar to the tr shell utility (though not quite as flexible). This program will switch all 0s with 1s and vice versa.

Length 9 Snippet

1!G;$p;h

This snippet is actually 8 bytes, but requires the -n parameter to sed to suppress default output, so as per standard code-golf rules, I'm counting this as 9. This program reverses the lines in the stream. So:

sed -n '1!G;$p;h'

is exactly equivalent to:

tac

Length 10 Snippet

s/[ <TAB>]+$//

This is a revisit of the (incorrect) length 6 snippet. This strips trailing whitespace (spaces and TABs) from lines.

Digital Trauma

Posted 2015-01-19T12:36:59.320

Reputation: 64 644

2

See also USEFUL ONE-LINE SCRIPTS FOR SED, which is basically how I learned sed

– Adam Katz – 2015-08-27T22:08:46.097

You have more votes. Can we have some more? – luser droog – 2016-01-15T03:37:33.910

2Your factoid 404'ed. – Wauzl – 2016-05-09T07:36:13.957

1Nice, but please note many of these use GNU extensions and are not standard—specifically length 3 (standard would be i\<newline>Hi<newline>), length 5 (standard would be sed -e :l -e bl or :l<newline>bl<newline), and length 10 (which needs the + turned to a * to work at all). Note that the length 9 snippet -n '1!G;$p;h' is standard, whereas tac is not. :) – Wildcard – 2016-11-10T07:59:01.813

1@Wildcard Yes - I've restricted this to GNU sed. – Digital Trauma – 2016-11-14T20:31:04.723

Your factoid contains code. – Erik the Outgolfer – 2016-12-16T17:47:10.637

39

Python

(mbomb007's post already has a plethora of Python snippets, but I thought I'd chip in with some quirkier facts)

Factoid

Python is a dynamically typed language with an emphasis on readability.

Length 1 snippet

1

In Python 3, the above is equivalent to True in the sense that 1 == True (and also 0 == False). Note that this doesn't necessary hold true in Python 2, where you can redefine the value of True.

Length 2 snippet

<>

<> is an obsolete comparison operator equivalent to !=. It still works in Python 2 (although its use is discouraged), and was removed altogether from Python 3.

Length 3 snippet

...

Python has a number of features which no builtin uses, but is there solely for the sake of third-party libraries. This Ellipsis object is one of them, and it is typically used for slicing. For example, if we have the following 3D numpy array:

array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

then a[..., 0] (equivalent to a[:,:,0]) gives all the first elements:

array([[1, 4], [7, 10]])

In Python 3 the ... literal can be used outside of the slicing syntax, which amusingly allows you to use it as a "to-do" marker in place of pass or NotImplemented:

def f(x):
    ... # TODO

Length 4 snippet

(1,)

A one-element tuple in Python.

Python has lists (e.g. [1, 2, 3, 4]) which are mutable, and tuples (e.g. (1, 2, 3, 4)) which are immutable. One common use for tuples is as dictionary keys, since lists aren't hashable.

A common beginner mistake is to leave out the comma above, i.e. (1), which is just the number 1 surrounded by parentheses. The one-element tuple is the only time you need a comma before the closing parens — it raises a SyntaxError if you try to put one in the empty tuple (), and is optional for tuples of length at least 2.

Length 5 snippet

0or x

There's a few things going on in this snippet, so let's take a look!

or is like || in many languages. In Python, A or B short-circuits, returning A (without evaluating B) if A is truthy, otherwise it returns B. For example, 1 or x always returns 1, as 1 is always truthy, and even works if x is not defined. On the other hand, 0 or x either returns x if x is defined, or throws a NameError if it isn't.

When golfing, we can usually drop the whitespace between a number and an or, such as 1 or x becoming 1or x. This is possible because 1or starts with a digit, making it an illegal Python identifier.

However there is one exception — 0or, which mysteriously throws a SyntaxError. Why? Because octal literals in Python start with 0o (e.g. 0o20 == 16), and the parser chokes when it reaches the r!

Note: In Python 2, octal literals may also start with a leading zero, e.g. 020.

Length 6 snippet

*x,y=L

This snippet demonstrates a special type of assignment in Python, where L is a list, tuple or any other sort of iterable.

In Python, you can "unpack" tuples and lists like so:

a,b = [1,2]

This assigns 1 to a and 2 to b. This syntax is also used for multiple assignment, such as

a,b = b,a+b

which is useful when writing a program that computes the Fibonacci series.

If the lengths on both sides don't match, then a ValueError is thrown. However, Python 3 introduced a new syntax, extended iterable unpacking (or more colloquially, "starred assignment") which allows you to do things like this:

*x,y = [1, 2, 3, 4, 5]

This assigns y to the last element, 5, and x to the rest of the list, i.e. [1, 2, 3, 4]. You can even do something like this:

a,b,*c,d,e = [1, 2, 3, 4, 5, 6, 7]

which assigns 1 to a, 2 to b, [3, 4, 5] to c, 6 to d and 7 to e.

Length 7 snippet

zip(*x)

zip is a function which takes a bunch of lists and, well, zips them up:

>>> zip([1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]

Note: In Python 3 a zip object is returned instead, so if you want a list like above you'll need to wrap the call in list()

It's quite a convenient function if you have two or more related lists, and you want to link up their respective entries.

Now say you want to unzip the list — how would you do so? We can try to use zip again, but unfortunately this gives:

>>> zip([(1, 4), (2, 5), (3, 6)])
[((1, 4),), ((2, 5),), ((3, 6),)]

The problem is that everything is in the one list, but zip takes the individual lists as separate function arguments. To fix this we introduce the * splat operator, which takes a list/tuple/etc. and unpacks them as function arguments:

f(*[1,2]) ==> f(1, 2)

And the result is:

>>> zip(*[(1, 4), (2, 5), (3, 6)])
[(1, 2, 3), (4, 5, 6)]

Length 8 snippet

x='a''b'

The first time I saw this, I was a little taken back — what does it mean to have two strings next to each other? The answer was simple:

>>> x
'ab'

Python merely concatenates the two strings! This is extremely useful for readability, since it allows you to break up long strings like so (note the surrounding parentheses):

x = ('This is a very long sentence, which would not look very nice '
     'if you tried to fit it all on a single line.')

Length 9 snippet

0!=2 is 2

You may already know that Python allows chaining of comparison operators, so 5 < x <= 7 is only true if 5 < x and x <= 7. If you didn't know that... then surprise!

Anyhow, lesser known is the fact that, since is/is not/in/not in are also comparison operators, they can be chained too. In other words, the above code is equivalent to (0 != 2) and (2 is 2), which is True.

Note: There are a few subtleties with the 2 is 2 half though, since is checks whether two things are the same object, not whether two things are the same value. Python caches small integers so 1+1 is 2 is True, but 999+1 is 1000 is False!

Length 10 snippet

x=[];x+=x,

What happens when you add a list to itself? If we try printing x, we get:

[[...]]

Fortunately, Python's print is intelligent enough to not explode trying to print recursive lists. We can then do a bunch of fun things, like:

>>> x[0][0][0][0][0]
[[...]]
>>> x[0] == x
True

This feature also works with dictionaries, and is one way of creating data structures with cycles, e.g. a graph.

Length 11 snippet

help(slice)

The help function is very useful for debugging in Python. When called with no arguments in REPL, help() starts a help session, in which you can look up documentation for functions/data types/etc. When called with a specific argument, help will give information on the related item.

For example, help(slice) gives the following information (truncated since it's quite long):

Help on class slice in module __builtin__:

class slice(object)
 |  slice(stop)
 |  slice(start, stop[, step])
 |  
 |  Create a slice object.  This is used for extended slicing (e.g. a[0:10:2]).
 |  
 |  Methods defined here:
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |
 | ...

As for slice, as we can see we can create slice objects for indexing. For example:

>>> L = list(range(10))
>>> L[slice(2, 5)]         # L[2:5]
[2, 3, 4]
>>> L[slice(2, None)]      # L[2:]
[2, 3, 4, 5, 6, 7, 8, 9]

Another useful function for debugging is dir(), which returns all names in the current scope when called without an argument, and returns all attributes of a given object when called with an argument.

Length 12 snippet

round(5.0/2)

What does this evaluate to? The answer depends on your Python version!

In Python 2, division between two integers results in integer division (i.e. 5/2 == 2) whereas in Python 3 we get float division (i.e. 5/2 == 2.5). However, this is division between a float and an integer, which should always result in a float. Why would we get different results then?

If we take a look at the documentation for round for both Python versions, we'll find the answer:

  • In Python 2, round tiebreaks by rounding away from 0.
  • In Python 3, round tiebreaks by rounding towards the closest even integer.

In other words, 5.0/2 = 2.5 rounds to 3 in Python 2, but rounds to 2 in Python 3. Rounding towards the closest even integer might sound weird, but it's actually called banker's rounding, and tries to treat positive and negative values similarly to reduce bias.

Length 13 snippet

class C:__x=1

Being object-oriented, Python has classes. The above is a class C which has a single attribute __x set to 1.

We can access class attributes using dot notation. For example, if we have the class

class MyClass(): my_attr = 42

then printing MyClass.my_attr would result in 42, as expected.

However, if we do the same and try to access C.__x as defined above, we get:

AttributeError: type object 'C' has no attribute '__x'

What's going on? C clearly has an __x attribute!

The reason is that attributes starting with __ emulate "private" variables, something which Python does not have. Python mangles the name of any attribute starting with __, appending the class name so that name reuse conflicts are avoided. In the above example, if we were really determined to access that 1, we would instead have to do

>>> C._C__x
1

Length 14 snippet

NotImplemented

Not only does Python have classes, it also has operator overloading. For example, you can have a class

class Tiny():
    def __lt__(self, other):
        return True

where __lt__ is the less-than operator. Now if we make an instance of Tiny, we can do this

>>> t = Tiny()
>>> t < 1
True
>>> t < "abc"
True

since we've defined __lt__ to always return True. Note that we can also do

>>> 42 > t
True

but the following breaks:

>>> t > 42
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    t > 42
TypeError: unorderable types: Tiny() > int()

Wait, how does that work? We haven't specified a behaviour for greater-than with Tiny, so it's not surprising that the last case breaks. But then how does an int (42) know that it's greater than our Tiny object?

Python has a builtin constant NotImplemented, which can be returned by a comparison special method. Let's try it out:

class Unknown():
    def __gt__(self, other):
        # __gt__ for greater-than
        print("Called me first!")
        return NotImplemented

Now if we make an instance of our new class:

>>> u = Unknown()

We can do this:

>>> t < u
True
>>> u > t
Called me first!
True

As we can see, what happened for u > t is that Python tried to call the greater-than method for Unknown first, found that it was not implemented, and tried the less-than method for the other class (Tiny) instead!

Length 15 snippet

x=[],;x[0]+=[1]

This is a bit of a fun one. First we assign x to be [], which is an empty list inside a tuple, i.e. ([],). Then we do x[0]+=[1] which tries to extend the empty list inside by the second list [1].

Now, remember that lists are mutable and tuples are immutable – what happens when you try to change a mutable object inside an immutable object?

>>> x=[],;x[0]+=[1]
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    x=[],;x[0]+=[1]
TypeError: 'tuple' object does not support item assignment

Oh so it gives an error, I guess that's to be expected. But what if we try to print x?

>>> x
([1],)

Huh? The list changed!

If you're curious about what's happening here, be sure to check out this blog post.

Length 16 snippet

@lru_cache(None)

Just add cache! This is a simple example of a decorator available in Python 3.

Suppose we have the following naïve Fibonacci implementation:

def f(n):
    if n < 2: return 1
    return f(n-1) + f(n-2)

As most introduction to programming courses may tell you, this is a very bad way of implementing Fibonacci, leading to exponential runtime since we're effectively just adding a lot of 1s at the base case. f(10)? Runs in a split second. f(32)? Take a while, but it gets there. f(100)? Nope.

But if we cache the results, things should get a lot faster. We could always use a dictionary for the cache, but let's try something else instead:

from functools import lru_cache

@lru_cache(None)
def f(n):
    if n < 2: return 1
    return f(n-1) + f(n-2)

As we can see, all I've done is import lru_cache from the functools module and added @lru_cache(None) before my function. @ denotes a decorator which wraps around a function, in this case for memoisation. lru_cache's first argument is maxsize, the maximum size of the cache – here we've set it to None to indicate no maximum size.

Now if we try to use it:

>>> f(100)
573147844013817084101

And it didn't even take a second!

Note: f(1000) leads to a recursion depth error, but that's a story for another time

Sp3000

Posted 2015-01-19T12:36:59.320

Reputation: 58 729

What range of small integers does Python "catch" for the is operator? – mbomb007 – 2015-04-06T16:37:00.603

@mbomb007 From this question, it appears to be -5 to 256. You can try -5-1 is -6 and 255+2 is 257 to test.

– Sp3000 – 2015-04-06T16:40:03.787

37

Jot

Factoid: I can define Jot with 2 upvotes, and prove that it's Turing complete with 8 (not using lengths 4, 6, or 7).

Length 1

1

This is an example of two functions in Jot. The first is the empty string, which evaluates to the identity function. The second is 1, which is Jot's grouping operator. 1 evaluates to λxy.[F](xy) (lambda calculus notation), where [F] is the program before the 1 (here, the empty string). So, this program is the function λxy.(λz.z)(xy) which simplifies to λxy.xy.

Length 2

10

Now we are introducing the other symbol in Jot: 0. Again if [F] represents the value of the program so far, 0 evaluates to [F]SK, where S and K are from combinatory logic. I've defined the entire language now.

Length 5

11100

I will now prove that Jot is Turing complete by defining a mapping from combinatory logic to Jot. This Jot program is the K combinator.

Length 8

11111000

This is the S combinator.

Length 3

1AB

Here, A and B are not part of Jot, but rather placeholders for an arbitrary expression. The expression AB in combinatory logic maps to 1AB in Jot, with A and B recursively transformed by these three rules. QED

Length N

1
10
11
100
101
110
[...]

Every natural number, expressed in binary, is a valid Jot program. Consequently, I can algorithmically generate more snippets of arbitrary length. Given enough upvotes, I can solve the halting problem.

Phil Frost

Posted 2015-01-19T12:36:59.320

Reputation: 191

2Two upvotes given. Now define the language. – John Dvorak – 2015-01-19T14:20:42.753

@JanDvorak working on it...it's been so long since I researched this thing that I forgot all of it :) – Phil Frost – 2015-01-19T14:22:24.907

@PhilFrost There are single combinators which are turing complete by themselves. – proud haskeller – 2015-01-19T15:02:42.353

1I don't see why this should continue getting more upvotes. You are simply going to generate random binary numbers of increasing length :| – Optimizer – 2015-01-19T15:18:51.123

@Optimizer with 5 votes I can give the next step in the Turing completeness proof. – Phil Frost – 2015-01-19T15:19:23.197

1You said so for upvote number 4. But here we are looking at a "random number you just generated" – Optimizer – 2015-01-19T15:21:00.743

@proudhaskeller Yes, but combinatory logic requires an infinite set of variables and parenthesis in its syntax. Jot has neither: 1 and 0 are the only characters in the language. – Phil Frost – 2015-01-19T15:27:44.687

I think you should evaluate all of the programs to the lambda equivalent. Im a bit curious what would the last one be... Also, the first one reduces to the identity function. – proud haskeller – 2015-01-19T15:32:05.657

@proudhaskeller I'll give it a try if you promise to check my work. – Phil Frost – 2015-01-19T15:46:04.887

@PhilFrost Sure. – proud haskeller – 2015-01-19T15:47:31.493

@proudhaskeller I'm pretty sure I've got something wrong, but I'm out of time for this. I've made it community wiki -- if you want to give it a shot feel free. – Phil Frost – 2015-01-19T16:23:59.650

1how can you solve the halting problem? I'm guessing it has something to do with using an infinite (number of infinite) program? – Filip Haglund – 2015-02-21T12:29:22.817

37

Matlab

Snippet 26 - iterate over matrices

This is something I just recently discovered. Usually you iterate over a given vector in for loops. But instead of vectors, you can also use matrices (rand(10) produces a 10x10 matrix with uniformly distributed numbers between 0 and 1).

for k=rand(10);disp(k);end

This then displays one column vector of the random matrix per iteration.

Snippet 25 - easy plotting

We know plotting is easy in matlab, but there is a super easy function ezplot (E-Z get it? It took quite a while until I finally got it, as I spelled Z always as sed instead of c, whatever...) Everyone likes elliptic curves:

ezplot('y^2-x^3+9*x-10.3')

elliptic curve

Snippet 24 - integration

The old fashioned word (but still in use in numerical computation) for integration is 'quadrature', can you guess what the result of the following one is?

quad(@(x)4./(1+x.^2),0,1)

Snippet 23 - images

Of course Matlab is also very popular among scientists who have to work with images (e.g. medical image analysis), so here is a very handy function. First argument is the image, second the angle and the third optional argument here tells the function to crop it to original size.

imrotate(rand(99),9,'c')

here

Snippet 22 - music

load handel;sound(y,Fs)

It will sound about like this (youtube link)

Snippet 21 - differentiate & integrate

polyint(polyder(p),c)

You can easily differentiate and integrate polynomials by using those two functions. When integrating, you can pass a second argument that will be the constant.

Snippet 20 - back to polynomials

p=poly(r);cp=poly(A)

Want the polynomial with the roots in r? Easy: p=poly(r). Want the characteristic polynomial of a matrix A? Easy: cp=poly(A). So roots(p) is exactly r (or a permutation of r).

Snippet 19 - another magic trick

fminsearch(fun,x0);

There are people who absolutely love this function. This basically just searches a minimum of fun with an initial value x0 (can be a vector) without any conditions on fun. This is great for fitting small models where you cannot (or you are too lazy) to differentiate the error/penalty/objective function. It uses the Nelder-Mead simplex algorithm which is pretty fast for functions where you cannot make any assumptions.

Snippet 18 - intro to polynomials

p=polyfit(x,y,deg)

Matlab has a nice solution for coping with polynomials. With polyfit you get a least squares polynomial of degree deg that approximates the points in x,y. You get a vector p that stores the coefficients of the polynomials, because that is the only thing what you need for representing a polynomial. If you go back to snippet 15, you can do the same thing by writing c = polyfit(x,y,2). So e.g. [1,-2,3] represents the polynomial x^2 - 2*x+3. Of course there are also functions for fitting other elementary, or arbitrary functions.

Snippet 17 - angles and discontinuities

unwrap(angle(c))

If you want to get the argument of a 'continuous' vector of complex numbers you often get back values that seem to have a discontinuity. E.g. angle([-1-0.2i,-1-0.1i,-1,-1+0.1i,-1+0.2i]) will get you [-2.94,-3.04,3.14,3.04,2.94] since angle only returns angles between -pi and pi. The function unwrap will take care of this! If you get a discontinuity like this, it will just add a multiple of 2*pi in order to remove those: '[-2.94,-3.04,-3.14,-3.24,-3.34]' This even works for 2d-matrices! If you just plot the argument of complex numbers with a negative real part you get the first graphics you'll get the first image, with unwrap you get the second one:

without unwrap with unwrap

[x,y] = meshgrid(-1:0.01:0,-0.5:0.01:0.5);
z = x+i*y;
imagesc(angle(z))
imagesc(unwrap(angle(z)))

Snippet 16 - scalar product

[1;2;3]'*[4;5;6]

Of course there are built in methods (like dot), but with the matrix-transformation operator ' it is as simple as that. If you do not know whether you have row or column vectors, you can just use a(:)'*b(:) where a(:) always returns a column vector.

Snippet 15 - linear least squares, the ugly method with the magic wand

[x.^2,x,x.^0]\y

x is the (column) vector with the values on the x-axis, y the noisy y-values. Type c=[x.^2,x,x.^0]\y and you get the coefficients of the 2nd degree polynomial. Of course you can use one of the billion builtin fit functions of matlab (how boring) why not use the magic wand?=)

x = (-1:0.1:2)';
y = 3*x.^2-2*x+1+randn(size(x)); %add some gaussian (normal) noise
A = [x.^2,x,x.^0];
c = A\y              %output: c = ]3.0049; -2.3484; 1.1852]
plot(x,y,'x',x,A*c,'-')

linreg

Snippet 14 - graphs

gplot(graph,x)

That is how to plot a graph. graph should contain a square adjacency matrix and x should be a nx2 matrix that contains the coordinates of each node. Lets make a random graph: graph = triu( rand(8)>.7) (make a Matrix that contains 0s and 1s, get only the upper triangle for an interesting graph). x = rand(8,2) then plot with some fancy styles gplot(graph,x,'k-.d')

graph (I declare this as modern art.)

Snippet 13 - meshgrid

meshgrid(a,b)

This is one of the most awesomest functions, simple but useful. If you want to plot a real valued function depending on two variables, you can just define a vector of values for the x-axis and one for the y-axis (a and b). Then with meshgrid, you can create two matrices of the size len(a) x len(b) where one has only the vector a as column, and the other has only the column has only the vectors b as rows. Usage example:a = -3:0.2:3;[x,y]=meshgrid(a) (if both vectors are the same, it is sufficient to just pass one.) Then you can just type z=x.^2+-y.^2 and e.g. mesh(x,y,z). This works for an arbitrary number of dimensions! So this is not only great for plotting, but also for getting all possible combinations of different vectors etc... (So, if you want to create a new code golf language, this should be in there, just make sure you use a shorter function name...)

mesh

Snippet 12 - plotting

plot(x,x.^2)

Take a vector x=-3:0.5:3 and and let plot do the rest. There are many more functions for plotting this is just a very basic one that you can use all the time. It would be already enough to write plot(v) and the data in v will be plotted against the array indices. How simple is that? If you want to style your plot, just add a string as a third argument: e.g. 'r:o' will make a red, dotted line with circles around the data points. If you want multiple plots, just add more arguments, or use matrices instead of vectors. Foolproof. plot

Snippet 11 - function handles

f=@(x,y)x+y

This is an example of a function handle that gets stored in f. Now you can call f(1,2) and get 3. Function handles in matlab are very useful for math functions (e.g. plotting) and you can define them in one line. But one drawback is that you cannot have conditionals or piecewise (and therefore no recursion). If you want this, you have to use the function statement and declare a new function, and each of those has to be stored in a separate file... (WHYYYYYY????)

PS: You'll get another funny easter egg if you type why in the console: They made a huge function that produces random messages like:

The tall system manager obeyed some engineer.
The programmer suggested it.
It's your karma.
A tall and good and not excessively rich and bald and very smart and good tall and tall and terrified and rich and not very terrified and smart and tall and young hamster insisted on it.

...which is very comforting if you are desperate enough to ask the console why...

Snippet 10 - How does my matrix look?

spy(eye(9))

As you know by now eye(9) creates a 9x9 identity matrix. spy just creates a that shows the zero/nonzero entries of the matrix. But you can also use it for displaying any binary 2d data. If you call spy without argument you'll get a nice little easter egg=)

spy on identity spy easteregg

Snippet 9

kron(a,b)

The kron function evaluates the Kronecker product of two matrices. This is very useful for discretisized multidimensional linear operators. I also used it every now and then for code golfing. You want all possible products of the entries of a and b? kron(a,b), here you go.

Snippet 8

5*a\b.*b

Ok here I mixed up 3 different operator. You can multiply any matrix by a scalar by just using *. (Then every entry of the matrix gets multiplied by that scalar). But * also performs matrix multiplications. If you prepend a dot you get the .* operator, this one multiplies two matrices of the same size but entry wise. (This can also be done with division operators like / and \.)

Next, the backslash operator can be used as left division (in contrast to / which performs right division as you are used to) but it is also the most powerful and characteristic operator of matlab: It performs a 'matrix division'. Lets say you have the system of linear equations A*x=b and you want to solve it for x, then you can just type x=A\b. And \ (you can also use / but that is less common for matrices) first quickly analyzes the matrix, and uses the results to find the fastest algorithm to perform this inversion-multiplication! (See e.g. here)

But you can also use it for under- or over-defined systems (where the there exists no inverse or where the matrix isn't even square, e.g. for least squares method). This really is the magic wand of matlab.

Snippet 7

[a,b;c]

Ok that does not look like much, but it is a very convenient tool: Matrix concatenation. A comma between two expressions means that they get concatenated horizontally (that means they have to have the same height) and a semicolon means that the previous 'line' will be above the next 'line' (by line I mean everything between two semicolons. Just a simple example: a = [1,2;3,4]; b = [5;6]; c =[7,8,9]; d=[a,b;c]; will result in the same d as d=[1,2,5; 3,5,6; 7,8,9]. (Get it?)

Snipped 6

eye(7)

This function produces a full 7x7 identity matrix. It is that easy. There are other functions like nan,inf,ones,zeros,rand,randi,randn that work the very same way. (If you pass two arguments you can set the height/width of the resulting matrix.) As I will show later, you can easily create and (and in a very visual way) concatenate matrices (2d-arrays) which is sooo damn useful and easy if you have to numerically solve partial differential equations. (When you solve PDEs the general approach is discretisizig the derivative operators, basically you will get just a huge system of linear equations that needs to be solved. These matrices normally are sparse (only very few non-zero elements) and have some kind of symmetry. That's why you can easily 'compose' the matrix you need.

Snippet 5

a(a>0.5)

I hope you are not getting tired by all the ways of accessing arrays. This shows an easy way to get all elements of an array that meet some conditions. In this case you get a vector of all elements of a that are greater than 0.5. The expression a>0.5 just returns a matrix of the same size as a with ones for each element that satisfies the condition and a 0 for each element that doesn't.

Snippet 4

a(:)

This again just returns the contents of a as a column vector (nx1 matrix). This is nice if you do not know whether you stored your data as column or row vector, or if your data is two dimensional (e.g. for 2d finite differences methods).

Snippet 3

1:9

You can easily make vectors (in this case 1xn matrices) with the semicolon operator. In this case you get the vector [1,2,3,4,5,6,7,8,9]. This is also particularly nice for accessing slices of other vectors as e.g. a(2:4) accesses the second, third and fourth element of the vector a. You can also use it with a step size, like 0:0.5:10 or so.

Snippet 2

i;

A semicolon suppresses output to console. You can see it as a good or a bad thing, but I like it for debugging stuff. Any line of calculation etc. will automatically print its result to the console, as long as you do not suppress the output by a semicolon.

Snippet 1

i

Complex number are a basic number type. (Too bad many people use i as a counting variable in for loops in which case it gets overridden.)

Intro

For those who do not know, MatLab is a programming language (with nice IDE that is also called MatLab?) that is first of all intended for numerical calculations* and data manipulation. (There is an open source counterpart called "Octave") As it is only** interpreted it is not very fast, but it's strength are that you can easily manipulate matrices and many algorithms are implemented in an optimized way such that they run pretty fast when applied on matrices. It also is a very easy language to learn, but I do not recommend it as a starter language as you will assume pretty bad 'programming' habits.

*As it is a interpreted language it can be very slow for expensive projects, but you have built-in parallelization methods, and you can also use multiple computers together to run a program. But if you really wanna get fast I think you still depend on C or Fortran or crazy stuff like that. But still many implemented algorithms (matrix multiplication, solving systems of linear equations etc) are heavily optimized and perform quite well. But if you program the same algorithms in Matlab itself, you're gonna have to wait=) (Something really unintuitive when you come from other languages is that if you vectorize your operations instead of using for loops, you can save much time in Matlab.)

**You can sort of compile your programs, but that mainly converts the source code to an unreadable file (for humans), that is not that much faster when executed.

flawr

Posted 2015-01-19T12:36:59.320

Reputation: 40 560

1I have this problem very often...setting i to something and then experiencing unexpected behavior when it is not the complex unit. – feersum – 2015-01-19T20:10:40.193

I tried to upvote but the unmatched asterisks in the Intro are preventing me :) – trichoplax – 2015-01-20T05:28:27.743

Oh I totally forgot about those=) Gonna complete these right now. – flawr – 2015-01-20T09:43:18.217

3Nice easter egg! If you type 'edit spy' you find an example of code obfuscation :-) – Abulafia – 2015-01-21T12:11:04.443

1I went to upvote this and then realized I already had. Alas, if only I could upvote it again. Keep 'em coming, @flawr! – Alex A. – 2015-01-21T15:30:40.570

The introduction is a bit out of date. Since Matlab does have Just In Time execution in recent versions, it has become quite straightforward to write code (with loops) that has similar runtimes as C++ for example. (Perhaps plus a few %) – Dennis Jaheruddin – 2015-01-23T09:08:25.153

I think this sentence isn't right, not sure what is should be: (you can also use \ but that is less common for matrices). Nice answer overall, look forward to seeing it grow. – Dennis Jaheruddin – 2015-01-23T09:14:11.640

@DennisJaheruddin Thanks, that should have been a /! Well what I've written is generally what I've heard so far, I have no experience when it comes to comparing with C++ etc (and I am using a 2009 version=). But I am running out of ideas now =/ – flawr – 2015-01-23T14:06:27.347

2

If you are running out of inspiration on things to show, I can recommend the Mathworks blog: On the Art of MATLAB by Loren Vershure Often they describe best practices that can be shown within the character limit. For curiosities consider Abandon Matlab, and for undocumented functions and features you can go to Undocumented Matlab by Yair Altman

– Dennis Jaheruddin – 2015-01-23T14:20:31.687

@DennisJaheruddin Oh thanks, I was not aware of thos websites, let's have a look=) – flawr – 2015-01-23T15:28:10.170

@DennisJaheruddin: Abandon Matlab is hilarious. – Alex A. – 2015-01-28T21:53:28.047

@flawr: Here's a suggestion for snippet 22: filter([0.5,0.5],.9,x) takes time series vector x and applies a moving average filter of window length two. – Abulafia – 2015-02-05T14:04:36.893

1

@flawr - For the factoid, it may also be cool to mention the fact that historically, MATLAB was originally created for the students in Computer Science at the University of New Mexico (Cleve Moler was chairman at the time) as an easy interface to the LINPACK and EISPACK (... now being superseded by LAPACK) without having to learn FORTRAN.... and because of its ease of use, it spread to other academic institutions very quickly :)

– rayryeng - Reinstate Monica – 2015-07-22T20:01:43.210

37

Bash

Factoid:

The extremely serious ShellShock bug was present in Bash since 1989, and remained undiscovered for a quarter of a century. Much of the joy of writing Bash is coming to grips with its many idiosyncracies and inconsistencies.

Length 1 snippet:

[

An alias for the test builtin, allowing code of the format if [ a == b ]; then - in reality [ is a standalone command, not a syntactical element, and ] is purely decorative (although required by [, its requirement is arbitrary and you can do away with it by using alias [=test).

Length 2 snippet:

||

Like logical or in most languages, but for processes. Will execute the command after the || only if the command before it returns non-zero.

Length 3 snippet:

x=y

Assignment. Nice and predictable... but unlike most other languages, extra spaces aren't allowed. Which is kind of funny because you can stick extra spaces pretty much everywhere else between things in bash, just not around the =.

Length 4 snippet:

$IFS

Internal Field Separator - this variable affects how Bash splits data for many built-in actions, such as iterating in for loops and populating arrays from strings. Used correctly it can be very powerful; but more often it's the cause of subtle and unpredictable bugs.

Length 5 snippet:

${x^}

Substitute the string in x, but with the first character capitalised! Such a frequently used feature that it has its own dedicated piece of language syntax.

Length 6 snippet:

x=($y)

Fill an array, x, from a string or list of elements y, splitting on whatever the IFS is currently set to - by default, whitespace. A very useful feature for advanced bash programming.

Length 7 snippet:

${x[y]}

Arrays! But wait, what's that... y is a string, not a numerical index? Yes indeed, Bash supports associative arrays! Many people don't know this. You just need to declare -A x first.

Length 8 snippet:

${x##*,}

Substitute x, everything up until the last , character (or whatever you specify). Useful to get the last field of a csv - this is something you can't so easily do with cut, which only counts fields from the left. % and %% allows the same to cut from the right; % and # were chosen for their location on the US keyboard so it would be clear which means left and which means right, but that doesn't hold much value for everyone not using a US keyboard :)

Length 9 snippet:

[ a = b ]

In most other languages, a single equals in a comparison operation would produce unintended behaviour in the form of an assignment. Not in Bash, though. Just don't omit any of the spaces, whatever you do!

Length 10 snippet:

if [ a=b ]

This is what happens if you forget about the mandatory spaces. Will not throw an error. Will always return true - even if a and b are variables that are unset, or whatever they're set to, doesn't matter - it'll always return true. Think about code like if [ "$password"="$correctpass" ] to see the fun potential of this "feature".

Length 11 snippet:

x=${y//a/b}

Regex-style substring replacement! Set x to the value of y but with every instance of a replaced with b.

Length 12 snippet:

[[:upper:]]*

Pattern matching - you aren't limited to just using the * wildcard in the shell, you can use any POSIX standard match such as alnum, alpha, digit etc.

Length 13 snippet:

function x(){

A bit of C syntax has mysteriously crept in! One of many completely different uses for curly braces, and another example of optional decorative elements to make Bash look more like other languages - either () or function can be omitted here (but not both). Also more fun with inconsistent spaces - a space after the { is mandatory, but not before the closing }, as in function x { y;}

Length 14 snippet:

echo {Z..A..3}

Yet another totally unrelated use of curly braces. Expands a range with a specified step. In this case, will produce every 3rd letter from Z to A. Useful for generating sequences without using seq, but cannot be used with variables, so has limited functionality.

Length 15 snippet:

echo {a,b,c,d}x

Another similar but not identical use for curly braces in sequence generation; prints ax bx cx dx, and is useful for generating a list of strings from a sequence or list in a single command. Again however, limited in usefulness as it can't be used with variables inside the braces.

Riot

Posted 2015-01-19T12:36:59.320

Reputation: 4 639

Actually, ] is not purely decorative. [ will refuse to function if its last argument isn't ]. – FUZxxl – 2015-01-26T21:36:41.253

Yes, but it serves no purpose other than cosmetics; and if you substitute [ with its other form test, then the ] can be omitted without changing anything else in the call - I'm simply making the point that it's not actual bash syntax, just visual sugar. – Riot – 2015-01-26T21:39:39.880

You're right in that it's not bash syntax, but the trailing ] is [ syntax and you have to provide it just like how you have to terminate a statement in C with a semicolon. – FUZxxl – 2015-01-26T21:40:30.457

It's true that it's mandatory, but not at all in the same way as the C semicolon. The requirement for it is entirely arbitrary, as seen if you simply alias [=test and then write if [ 1 = 1; then etc. But I'll clarify my wording to take your point into account :) – Riot – 2015-01-27T00:15:18.947

1Regarding the function x(){ syntax: You can drop the parens, as you say, but you can also just drop the function part. In fact, that's how POSIX shell defines functions, so it's more portable that way. You could define a full function in 13 characters. For example: x(){ startx;} – kojiro – 2015-01-29T02:02:54.587

@kojiro Yes, very good point :) I'll edit to mention that "function" is also optional. – Riot – 2015-01-29T20:12:17.103

37

APL

Factoid

APL (A Programming Language) started out as an interpreter for a formula notation devised by Ken Iverson. When the language was designed, people used teletypwriters to communicate with computers. The character set of these was limited, but due to their construction, one could put multiple characters into the same position to compose complex characters. This feature is heavily used by APL, contributing to its infamous reputation as a read-only language.

You can try out most of the examples on http://www.tryapl.org.

Length 1

The character , called lampshade, both for its shape and for the enlightment you get from its presence, introduces a comment. Historically, it was created by overstriking a (jot) and a (up shoe).

Length 2

⍳3

The monadic (one argument) function (iota) generates a vector of the first few natural numbers. For instance, the aforementioned ⍳3 would yield 1 2 3, the vector of the first three natural numbers. On some implementations of APL, it would yield 0 1 2 instead, this depends on the value of ⎕IO, the iota origin.

Length 3

5\3

As opposed to the monadic , the dyadic \ (expand) function copies the argument on the right as often as the argument on the left; thus, 5\3 yields 3 3 3 3 3. You might want to play around with vector arguments (like 1 2 3\4 5 6) to see what it does then.

Length 4

A←⍳3

This assigns to A the value of ⍳3. (left arrow) is the assignment operator. An assignment doesn't have to be the leftmost thing in a statement; assignments are parsed like function calls and yield the assigned value for further use.

Length 5

∘.×⍨A

A three by three multiplication table, that is,

1 2 3
2 4 6
3 6 9

This is a little bit complicated, so let me explain. ⍺∘.f⍵ (read: alpha jot dot f omega) is the outer product of and over f. The outer product is a table of the result of applying f to each possible pair of elements from and . In this example, f is × (multiply), yielding a multiplication table. The operator (tilde diæresis) commutes its arguments, that is, ⍺f⍨⍵ is equal to ⍺f⍵ and f⍨⍵ without a left operand is equal to ⍵f⍵. Without the commute operator this snippet would be a∘.×a. The outer product operator is very versatile; check out what happens if you substitute = for ×!

Length 6

{×/⍳⍵}

A factorial function. A pair of curly braces encloses a dfn (dynamic function), that is, an anonymous function (cf. lambda expressions). The arguments to a dfn are bound to the variables and or just if the dfn is called as a monadic (single argument, as opposed to dyadic, two argument) function. We apply to the right argument, yielding integers from 1 to . The / (slash) operator reduces, that is f/⍵ inserts f between the items of . For instance, +/⍳5 is just 1+2+3+4+5. In this case, we reduce with ×, yielding the product of the items of ⍳⍵, which is just the factorial of .

Length 7

2×3*4+5

Yields 39366. ⍺*⍵ (alpha star omega) is raised to the power of . APL has a very simple precedence rule: Everything is evaluated from right to left, all functions are right-associative. Operators bind stronger than functions and are evaluates from left to right. Thus, the expression above with explicit parentheses would be written as 2×(3*(4+5)) as opposed to the usual (2×(3*4))+5.

Length 8

¯1+3 3⍴A

This snippet yields

0 1 2
3 4 5
6 7 8

and demonstrates two important concepts: The first concept is the (rho) function, which reshapes its right argument to the shape specified in its left argument. The shape of an array is a vector of the lengths of each axis in the array. The shape of a scalar is the empty vector. Thus, 3 3⍴A reshapes A into a three by three matrix. The second concept is how addition is used here: We add ¯1 (overbar one), meaning negative one (¯ is a prefix to specify negative numbers, while - is an operator) to an array. The two operands have different shapes, so the operand with the lesser shape is distributed onto the other operand, subtracting one from every item in the generated matrix.

Length 9

+.×⍨3 3⍴A

A, reshaped to a 3 by 3 matrix, multiplied with itself. The . (dot) operator takes two functions and constructs an inner product, where the first function represents addition and the second function multiplication. A plain, old, matrix multiplication is +.×, a common variant is ≠.∧ (where is not equal and (up caret) is logical and) for boolean matrices; many interesting things can be modelled as an inner product with certain operators in place of + and ×.

Length 10

(.5×⊢+÷)⍣≡

(read: left parenthesis dot five multiply right-tack plus divide right parenthesis star-diæresis same) Compute the square root of a real using the Babylonian method. The left argument is the number you want to compute the square root of, the right argument is the initial guess for the square root. I originally wanted to provide a meaningful initial guess, but I ran out of characters (append to use the number itself as the initial guess).

So how does this work? Let's start with the left part, (.5×⊢+÷), first. This expression uses tacit notation originating in J which was later ported back to Dyalog APL. Tacit notation is a bit hard for beginners, so please read this section carefully. An isolated sequence, such as +/÷≢, which the “normal” parsing rules do not resolve to a single part of speech is called a train. A train of two or three functions produces a function and (by repeated resolution), a function train of any length also produces a function. A train of three functions fgh behaves like {(⍺f⍵)g⍺h⍵}, that is, f and h are applied to the arguments of the resulting function and the result of these are applied to g. A train of an array and two functions like Afg behaves like {Af⍺g⍵}, this is, g is applied to the arguments of the resulting function and A and that result are applied to f. A train of two functions has a semantic, too, which is explained in the documentation but not used in this example.

In this particular train, one new function, (right tack) is used. It behaves like {⍵}, yielding its right argument. Thus, the entire expression is equal to {.5×⍵+⍺÷⍵}, which is just the iteration step of the Babylonian formula. It is easy to see how tacit notation benefits the golfer; it allows you to shave of quite a few precious characters where applicable.

The last piece of the puzzle is the (star diæresis), power operator. If the right argument is an array, f⍣A⍵ applies f to a total of A times. For instance, f⍣3⍵ is equal to fff⍵. The count can be negative, in which case APL tries to infer an inverse function of f and applies that. If the right argument to is a function, too, f⍣g⍵ applies f to until (fY)gY where Y is the result of the repeated application of f to . Notably, if g is = (equal) or (same), f⍣≡ computes a fix point of f. This is exactly what we need for the Babylonian method! We want to iterate until the result converges. Lastly, if applied to a pair of things is invoked as a dyadic function, the left argument is bound to f on the left, i.e. ⍺f⍣g⍵ is equal to (⍺∘f)⍣g⍵ where A∘f behaves like {Af⍵}.

FUZxxl

Posted 2015-01-19T12:36:59.320

Reputation: 9 656

You've got more votes! Can we have some more? – luser droog – 2016-01-14T05:59:28.533

@luserdroog Sure, let me think of some more. – FUZxxl – 2016-01-14T09:16:06.597

May I edit and extend this? – Adám – 2016-07-12T05:33:28.413

@Adám Yes, please. – FUZxxl – 2016-07-12T14:19:52.707

∘.×⍨a gives me a value error. Am I using it correctly? – Cyoce – 2016-09-13T21:55:47.533

@Cyoce Have you set a to something before doing that? – FUZxxl – 2016-09-13T22:49:15.727

@FUZxxl I see you edited the a to be uppercase. That appears to have been the issue – Cyoce – 2016-09-13T22:54:30.240

@Cyoce Yeah, I don't know what I did there. – FUZxxl – 2016-09-13T23:05:45.803

35

CJam

Try the below snippets here

Length 20 snippet:

q~{]__~z\z<=\~*0>*}*

A min-mod calculator. An excerpt from the question :

The minmod function is a variant of the familiar min, which appears in slope-limiting high-resolution schemes for partial differential equations. Given a number of slopes, it picks out the flattest slope, while taking care of relative signs between the slopes.

The function takes an arbitrary number of parameters. Then minmod(x1, x2, ..., xn) is defined as:

  • min(x1, x2, ..., xn), if all xi are strictly positive
  • max(x1, x2, ..., xn), if all xi are strictly negative
  • 0, otherwise.

Length 18 snippet:

l'[,65>Dm>_el+_$er

A ROT13 encoder. Shifts only a-zA-Z characters from the input string via STDIN

Length 15 snippet:

T1{_2$+}ri2-*]p

A full program to print the first N numbers from a Fibonacci series where N is provided as an input via STDIN.

Length 12 snippet:

{{_@\%}h;}:G

A simple GCD function. This can be used like 2706 410 G to get the GCD on stack.

Length 11 snippet:

123456 789#

# is the power operator. This snippet shows a cool feature of CJam that it supports BigInts for almost all mathematical operations. So the output of the above code is

1596346205622537943703716803040694151242100030904924074732295184521676912291137885341977590649991707684635184329980991487148618486236239062505001539322685142817506810040361209550544146292158784625519911512640361780862459268161619223326802388689703997604303632605734938879647069477372395799326590488746599202521617640394227957532720581758771344616555153473551874187964029973716015080326283503474062024803237072761129557356772954771383125420283743787215768524095651476398918270831514362626616089349128838080859262141293069421199363839940462244772673481244848208112002212957221705577938865719802035511067875502253218277834350725436729497351901219311577128600087062378434520948898301738545267825952998284599001356281260973911216650526574435975050678439968995805415462116669892745933523276658479456263859786003695570642598885206779863730608803831608206418317758451327165760242416052588688579435998154295782751455020445483571514197850814391880423853968520336337963918534259580183058727377932419280412466915889059399591196961188841001024998633317094826403760131868252088477018937989608302521450181593409274231460335072324865982559395114735391976545471553525054490202974741119144469523879456646833238659929705233941114530149037245274032070536718197592615630616792756562341411027203615235147973615347081993563361626845258162606172599728677944001956482301240050182368840648532697569098833480384074404562991348377266778603059081932412368912313845464302833428950934701568958836851009236647605585910687215977468114323293396641238344799575626940766355697576957869656153567798618227770961980620119004224798449940378878601283741944503399682599666873704888519152796472231721010884561046439019823540214190109829183178504573391524533915085342799888899681052113605127068137552531204917650779012455136663716975904242872042805633443567570913936237754642040107392687168596924804730637819953463737212774674563401663682370631910559669378413063684132477269578881395521544729393136204246705936061735379354437327940116154383441927197123218522827575163913310005036963663583344508839784971260123709283218409462028161021477446586507813599051643059982983426688872855309396405653159417356549291603532443699350168178837164682957610433456205211423600319694496115159970718912091395232327389520091646132878609779171226748990343349416763319432268713023302555895744813731889452605219001900815755497209921418814092923394321459962373890912709775151652200071533644718727513889263907829300496554849544461628702471995210369421320165755673222520834013956492183306187393652197405863508709529644837118590847002900783148394313160749018413291215958936871830666201928218294362550829287373305552379418641499562597137520153409556227576809855521876196531587454478159211299517511047868125975115347272184123454929507976958328038242400918390689757262398695703472270927183494613959476164389143107240083171566284628032072645081703351075328092783401422849512230275075331561337345714881104575020436358133210849231625973013523497330004645467493618279226202227586584610761439335895760888873155403816627190368675397978355381544497413492223577022267403347927237298551052219150516984577176643706356698282552857754120841266435149587248192704898338826251727748499150285409036076919533685800933215325289882260771526293167171975367192287689881199864600661035143522211647660445960687046757311913589429739868592726372013684511683081229044622752191694278221303073075505531920922815724661725685493922212700535444400760813940151761980008355835574184921854364539924999643954874549857103642483664109073938527328920827803218865362851320233433429604394590974694396314165313743853607609394553133883545319222169958204731303672940856293527174545435349105954532301106962634516087237739490953930886293289854731305112253177512851251930821765454042415085420000484369355605183062368648992392499663861508991984554431113080399485470268940148600970493633737364443822752829774334511729579419931500217970224646496435527826186627011323464848141074486509849545954714213290443775688291020289759390171236344528896

Length 10 snippet:

"`%W_"_W%`

We've already done quine, lets reverse it!. This is one of the shortest reverse quine in CJam. Reverse quine is a quine which prints its sources code in reverse order.

Length 9 snippet:

5,K,+_&S*

This snippet showcases a lot of features of CJam,

5, "create an array of numbers 0 to 4"
K, "create an array of numbers 0 to 19"
+  "List concatination"
_  "Duplicate top stack element"
&  "Set distinct operator in this case"
S* "Join array elements with space character"

Length 8 snippet:

"`_~"`_~

One of the smallest possible quines in CJam. This is a true quine in a sense that it does not actually read the source code in any manner. (Reading the source code is not even possible in CJam)

Length 7 snippet:

"AB"_m*

m* creates all the Cartesian products of the top two stack elements. For instance, the above code will put ["AA" "AB" "BA" "BB"] on stack, which is the cartesian product of "AB" and "AB".

Length 6 snippet:

"_~"_~

A nice looking repeated code. DO NOT run this :) . This representation of code is the basis for the simplest quine in CJam. You put string "_~" on stack, make a copy (_) and evaluate it. Which in turns does the same thing again (and again ..) until you reach maximum recursion exception.

Length 5 snippet:

{A}:F

This is how a basic function works in CJam, The above expression assigns the code block {A} to variable F. Now in your code, you can put F anywhere to run the code block (and get 10 in this case)

Length 4 snippet:

"A"~

You can evaluate any code block or string or even a single character using ~. The above expression results to 10

Length 3 snippet:

Kmr

A typical random number generator from range 0 to K i.e. 20.

Length 2 snippet:

es

This gives the current timestamp (milliseconds from the epoch). CJam also has et for local time in a more usable format which returns an array comprising of the various parts of the current time ( day, hour etc).

Length 1 snippet:

A

CJam has almost all capital alphabets as predefined variables. A is 10, B is 11 and till K is 20. P is pi (3.141592653589793), N is new line and many others. These can come very handy when you need initial values in variables, or even when you need two digit number in 1 byte.

Factoid

CJam is inspired by GolfScript but builds a lot of features on top of it including support for a network GET call :D

PS: I will try to update the answer every 5 upvotes or every 2 hours (which ever is earlier)

Optimizer

Posted 2015-01-19T12:36:59.320

Reputation: 25 836

There are some issues with your ROT13 example :p But I'm impressed with the quine, I think I'll borrow it :) – aditsu quit because SE is EVIL – 2015-02-01T17:44:48.237

@aditsu what is the issue ? – Optimizer – 2015-02-01T17:46:56.013

It changes the case of n-z letters. Also, it has an @ for no reason, you can put the D there instead. – aditsu quit because SE is EVIL – 2015-02-01T17:49:48.743

@aditsu Pretty sure that its a ROT 13 across a-zA-Z range and that is the reason for case change. Can you not read it ? its only your own language :P @ is there for 18 chars I guess :D – Optimizer – 2015-02-01T17:52:26.740

That's not what ROT13 normally does. I don't understand why you're asking if I can read my own language, the issue is not about understanding what the program does, but about the fact that it doesn't do what's expected. – aditsu quit because SE is EVIL – 2015-02-01T17:54:53.517

@aditsu fixed. The fact that you started with "there are some issues" without telling the issue directly :P – Optimizer – 2015-02-01T18:11:44.290

Very nice! And I just wanted to see if you would notice what's wrong. – aditsu quit because SE is EVIL – 2015-02-01T18:22:01.683

@aditsu I had to look up on Wiki about the actual definition :D – Optimizer – 2015-02-01T18:28:24.573

"_~" <(Nice language you got there.) – DJgamer98 – 2016-11-11T12:15:52.820

34

Common Lisp

Lisp (from LISt Processing) is one of the oldest languages still in use today (only FORTRAN is older). It is notable for being the first language where code is data and data is code; called homoiconicity. It was also the first language to have garbage collection. Originally designed by John McCarthy in a 1958 paper as an entirely theoretical language, it became a real language when Steve Russel realized that the eval function could be implemented on a computer. It's most prevalent in Artificial Intelligence, and is instantly recognizable from its preponderance of parentheses. Common Lisp was designed to unify many of the older Lisp dialects into a more standardized form.

I'll be trying for every snippet to be runnable on it's own, though not necessarily do anything of value. Additionally, because I'm using Common Lisp, the fundamental concepts and a lot of the syntax apply in other dialects, but certain functions won't work in, say, Scheme.

Length 1

*

Because of the emphasis on the use of S-Expressions and lists for coding, there're very few valid expressions in Lisp that don't contain parentheses, called atoms. Anything typed directly into the REPL (read-eval-print loop) is treated as a variable and evaluated as such. * holds the previous value that was printed by the REPL.

Length 2

()

This is the empty list, one of the most important symbols in Lisp. Every proper list in Lisp is terminated with an empty list, similar to how every proper string in C ends with \0.

Length 3

(*)

This is a basic function call, which consists of a symbol wrapped in parentheses. Lisp doesn't contain operators, they're just functions too. I picked multiplication specifically because it's not actually a binary function; the multiplication operator in Lisp takes an indefinite number of arguments. If it is given no arguments it returns 1, the identity operator for multiplication.

Length 4

`(1)

This is a cons cell, which is just another way of saying it's a pair of elements. In Lisp, each list consists of cons cells connected to cons cells, where the first element (the car) is the value and the second element (the cdr) points to the next cons cell. This forms the basis of Lisp being based upon linked lists. This particular cons cell has 1 as the car and the empty list as its cdr.

Length 7

(not t)

I want to touch on truth values in Lisp. This would return nil. In Common Lisp, t is the symbol for true while nil and () represent false and are equal to each other, but note that this definition isn't standard for all Lisp dialects; Scheme, for example, distinguishes between #f for false and '() for the empty list.

Length 9

(cdr ())

As I said before, the cdr is the tail element of a list, which you can get with the function cdr. Likewise, you can get the head element, the car, with the function car. Pretty simple, right? The car and cdr of the empty list are both nil.

Length 10

(cons 1 2)

Finally, enough length to start working with lists. cons creates a cons cell with the first parameter as the car and the second as the cdr. But instead of printing out (1 2), it gives (1 . 2). Going back to the length 2 snippet, a proper list is supposed to end with the empty list, so the cdr of the last cons cell should point to the empty list. In this case, the last cons cell points to 2, so Lisp informs us that we have an improper list, but still allows us to do it, like how you can make a C-string without a \0.

Length 11

(cons 1 ())

Now we have created our first properly formed list. It's a single cons cell with a car of 1 and a cdr of (). You'll notice that for every other list, I lead it with a backquote/tick; any other proper list would attempt to evaluate its first argument as a function with the remaining elements as parameters. Strictly speaking, () isn't a list though; it's a symbol composed of a ( and a ) that represents the empty list. Lisp allows you to use almost any printable character in a symbol name and will let you redefine any symbol as you want to.

Length 12

(cdr `(1 2))

This would output (2), not 2 as some people would guess. Remember, each cdr is supposed to point to either another cons cell or the empty list; obviously 2 isn't the empty list, so it must be another cons cell the a car of 2 and a cdr of ().

Length 13

'#1=(1 . #1#)

This would produce a circular list with just the single value 1. If printed, it would print “(1 1 1 1 ...” forever, so that in practice it can be considered an infinite list (on which you can do cdr infinite times to obtain always the same result, itself!). Unless one assigns T to the global variable *print-circle*, in which case it will be printed as #1=(1 . #1#).

Candles

Posted 2015-01-19T12:36:59.320

Reputation: 683

That last edit! Quick, someone make an Beatles-themed esolang:D – fede s. – 2016-03-23T23:53:15.957

1@fedes. John McCarthy, Paul McCartney... the language shall be called CarthyCartney. – cat – 2016-04-28T02:40:03.740

33

GNU Make

I'll go out on a limb on this one. I think this may well be the first time that make has been featured in PPCG.

Factoid

Make may be considered to be a functional language.

Length 0 snippet

I don't think length 0 snippets are required, but here is one anyway. I think this might be the most useful of all length 0 programs. With an empty Makefile (or even no makefile at all), make still has a bunch of built-in rules. E.g. there are default built-in rules to compile a .c file into a .o or binary, given the .c file exists in the current directory. So if we do:

make hello.o

make will find the .c to .o rule and compile hello.c to give hello.o

Similarly if we do:

make goodbye

If there is a goodbye.c file in the current directory it will be compiled into the goodbye binary.

Length 1 Snippet

TAB

Yes, the TAB character. While this doesn't do much on its own, it has great significance in Make. Specifically all recipe lines following a target definition in a rule MUST start with a TAB. This causes all sorts of frustrations when debugging makefiles when TABs and spaces get mixed up.

Length 2 Snippet

$@

This is an automatic variable for use in recipes. It will expand to the filename of the target of the rule. There are other useful automatic variables.

Length 3 Snippet

a:=

Shortest simply expanded variable assignment. The variable a is set to "" immediately when the Makefile is first parsed. If instead we do a=, then the assignment is recursively expanded, i.e. expansion is deferred until the time the variable is actually referenced.

Length 4 Snippet

W:;w

Shortest marginally useful complete rule specification. This defines a target W with a rule that simply runs the w shell command. Thus

make W

is equivalent to:

w

This is an alternative rule syntax in that the recipe follows the target on the same line separated by a new line. More commonly the recipe lines immediately follow a separate target line, with TAB characters starting each recipe line.

Length 5 Snippet

$(@D)

Another automatic variable. Similar to $@, but this expands to the directory portion of path, with the filename and trailing / removed.

Digital Trauma

Posted 2015-01-19T12:36:59.320

Reputation: 64 644

Maybe some string functions like $(basename ) or $(patsubst )? (eg.)

– luser droog – 2016-09-11T06:36:28.880

32

Marbelous

Length 14 snippet

}0}1
Mulx
HxHx

This snippet shows off some more of Marbelous libraries and introduces a new concept, namely, multi-cell boards. The Mulx board takes two marbles as input and outputs 2 marbles. Marbles that enter the leftmost cell of the Mulx will correspond to the }0 devices in that board and the rightmost cell to }1. Analogously, the outputs will come out of different cells as well. The width of a board can be calculated as MAX(1, highest output device + 1, highest input device + 1) cells that don't correspond to an input device will trash any marble that falls upon them.

Length 13 snippet

7E
??
>Y!!
{0

This is a board that will spit out a random printable ascii character on each tick. Marbelous has two ways of generating random values. There is ?? which returns a random value between 0 and the input marble it receives, inclusive, and ?n: ?0 up to ?Z respectively. Which act very similar to ??. We also have !! which terminates the board even if not all outputs are filled. Can you figure out how the ?n devices could be implemented as boards in Marbelous using ???

Length 12 snippet

}0}1
Fb//
Dp

Here we see a few library functions of Marbelous in action. Fb outputs the nth fibonacci number where n is the input marble. Dp prints the input marble to STDOUT as a decimal number. These are both implemented in Marbelous and can be called upon when you check include libraries in the online interpreter, for the python interpreter, you have to explicitely include each file. The inplementation of these boards can be found on github. Note that this particular program takes 2 inputs and will call the Fibonacci board two times. Boards that are called are return within one tick of the board that called them.

Length 11 snippet

}0}0
{<{0{>

This one needs some explanation. The }0 devices are imputs, since they have the same number (0), they will contain the same value when this board gets called. The three devices on the lower row are outputs. {< outputs to the left of the board, {0 outputs underneath the first cell of the board and {> outputs to the right. Output is only pushed when all distinct output devices are filled. In this case however, the right output device is never reached. The board will exit because of lack of activity and output the two values it has anyway. Can you imagine how one could implement /\ as a Marbelous board?

Length 10 snippet

..40
FF
\\

There's a few things that play an important role in Marbelous here. Firstly, there's addition. If you trace the path of the two marbles on the board, you'll notice that they'll end up on the same cell at the same time. When this happens, they'll be added together. (fun fact: at some point it was considered that instead of being added together, the marbles should form a stack) However, Marbelous is an 8 bit language, So adding a marble to FF is equivalent to subtracting 1 from it.

Length 9 snippet

00
\\/\]]

This is the shortest way to implement a rudimentary version of cat in Marbelous. 00 \/\ Is a loop that puts a 00value marble on the ]] device every second tick. This is an STDIN device. When a marble lands on this device, it tries to read the first character from STDIN, if there is one, it gets pushed down (and in this case printed again). If there isn't one, The original amrble gets pushed to the right. (and in this case trashed)

Length 8 snippet

}0
~~
{0

This snippet shows a few features. Firstly it takes input through }0. In this case this is the Main Board and this will be replaced by the command line input. You can also call this function, in that case, the argument will be taken instead of the command line input. Then there's ~~, which is a bitwise not operator. After that, we get to }0, If all }n devices are filled, these values are returned as the functions return values. (Marbelous supports more than one return value per function)

Length 7 snippet

00
\\/\

This is the most compact infinite loop you can create in Marbelous. The \\ device pushes any marble to the right, /\ copies a marble and pushes one copy to the left and another to the right. Since the board is only two cells wide, the marble to the right gets trashed though.

Length 6 snippet

46MB75

Here's an example of recursion, MB (the implicitly named main board gets called on every tick, but not before Printing Fu to STDOUT on each call. (Resulting in the following: FuFuFuFuFuFu... This obviously overflows the callstack.

Length 5 snippet

2A
++

Some arithmetic, The marble with value 2A falls down on teh first tick and the finds itself on the ++ cell. This is an operator. This particular operator increments any marble that land on it and lets it fall down. The marble now has value 2B and falls off the board. This prints + to STDOUT.

Length 4 snippet

:
24

The two interpreters disagree here, I've given the first board of the file a name in this example (The name is an empty string). The python interpreter assumes this is the Main board and calls this board upon running the program (which prints $). The javascript interpreter doesn't find the Main Board and thus no entry point. This can be useful when writing a library file for Marbelous.

Length 3 snippet

:Bo

This is a named board, with no body, we can call this board by Writing Bo in a cell of any board (including Bo itself)

Length 2 snippet

3A

This code is the body of a 1x1 cell (each cell is two characters wide) board, implicitly named MB (for Main Board). It prints the ascii value of the hexadecimal value of 3A when the marble falls off the board. The output of this program just so happens to be the source code of:

Length 1 snippet

:

Along with #, this is one of the two the only valid 1 character programs in marbelous. # is an indicator of a comment an therefor not very interesting. : tells marbelous that you're about to declare a board. Neither of teh two compilers care that you don't actually name or define the board. The program doesn't do anything.

factoid:

Marbelous was developed by people on this site, some names that were in the running for this language were Rube and simply Marbles.

overactor

Posted 2015-01-19T12:36:59.320

Reputation: 3 500

2beat me to it. nice snippets! – Sparr – 2015-01-19T16:24:52.910

your length 12 snippet seems to take two inputs, and print out two different fibonacci numbers. was that intentional? – Sparr – 2015-01-21T17:50:14.797

@Sparr, yes it was to showcase how functions work in Marbelous a bit. – overactor – 2015-01-21T20:41:36.403

maybe add that to the explanation? from what you wrote, I'd expect the snippet to take one input and output one fib number. – Sparr – 2015-01-21T20:54:12.667

I really hope you get to 40 points so my fibonacci function will fit... – Sparr – 2015-01-21T20:55:26.327

If you mark this as community wiki, I'd be happy to keep updating it. – Sparr – 2015-01-25T00:51:23.303

31

Pyth

For further snippets, I'll be posting solutions to golf challenges and a link to the problem.

Length 17:

<ussC,cG\_GUQ*zQQ

Find the first n characters of the infinite sequence formed by repeating the input string forever, then filling in its underscores with the sequence itself, then repeating that forever.

Fill In the Blanks

Length 14:

#QX=Qhf>FT.:Q2

Given a list of unique elements, sort the list by swapping pairs of neighboring elements, printing out all intermediate results.

Rearranging a set of numbers into order

Length 13:

?hu]+HG_UQYQY

Create the following structure: [0, [1, [2, [3]]]].

Home on the Range of Lists

Length 12:

uxyG*HQjvz2Z

XOR multiplication.

XOR multiplication

Length 11:

lfqSzST.:wz

Count how many substrings of the first word are anagrams of the second word.

Detecting anagrams within a Parent String

Length 9:

fqJjQT_J2

Find the lowest base in which the input is a palindrome.

Lowest-Base Palindrome

Length 5:

!%lQ1

Check whether the input is a power of 2. Take the log base 2, take the result mod 1, and take the logical not.

Check whether an integer is a power of 2 without using +,- operations

Length 4:

sjQ2

Calculates the hamming weight of the input by adding up the base 2 representation of the input.

Count the number of ones in unsigned 16 bit integer

Length 3:

^G2

^ on sequence, int, gives the cartesian product of the first argument with itself n times, where n is the second argument.

In this case, since G is the alphabet (abcdefghijklmnopqrstuvwxyz), ^G2 gives all 2 letter strings, aa through zz.

Length 2:

lT

l, while normaly serving as len(), can also be used as log base 2. Since T is the variable initialized to 10, this prints 3.3219280948873626, log base 2 of 10.

Length 1:

H

H is the empty dictionary (hash-table) in Pyth, and is the only way to get a dictionary in Pyth, short of using v (eval) or $ (Python literal).

Factoid:

Pyth has no multi-character constructs other than literals. Also, Pyth compiles essentially one-to-one into Python.

isaacg

Posted 2015-01-19T12:36:59.320

Reputation: 39 268

Was your factoid added before you have commands that start with .? – Leaky Nun – 2016-05-24T12:41:37.320

@LeakyNun Yes.. – isaacg – 2016-05-24T21:21:55.947

31

SAS

Factoid:

SAS is a data manipulation 4th generation language dating all the way back to 1966. Despite its age, it is still widely used to this day, particularly in financial and pharmaceutical environments where a large legacy codebase has been built up over the past few decades.

Length 1

;

To the best of my knowledge, this is the only complete and valid SAS statement of length 1 - a null statement.

Length 2

x;

SAS was born out of an effort to get code from one platform working on another. It has many OS-agnostic commands for interacting with the host operating system. The x statement is one of these. A null x statement opens up a command prompt / terminal for user input.

Length 3

%a:

As well as the primary language (consisting mainly of data steps, procs and global statements), a macro language was added in SAS 5. With 3 characters, we can define a 1-letter label for use with a macro %goto statement.

Length 4

run;

Analysts typically write SAS programs in an interactive environment (the SAS Enhanced Editor window). A run statement is required in order to tell SAS to execute all the (non-macro) code that's been compiled since the last run statement. As there is often a lot of back-and-forth editing and re-running of various steps within programs, it is quite common to see a run statement at the end of every data step and proc in a program, even though most of them are probably not necessary when running the whole thing from end to end.

Length 5

quit;

Some SAS procs support multiple sequentially executed run groups and will therefore not terminate until a quit statement is issued. Others do not and will throw an error if they receive a quit statement. Still others accept only a quit statement and will throw an error if they receive a run statement. Working out which are which can be rather frustrating for new users.

Length 6

set a;

SAS data steps usually operate in an implicit loop from an initial data statement to a final run statement (or the start of another data step, global statement, or proc). Each time a set statement is executed, SAS reads the next record from the input sas dataset(s) into an area of memory known as the Program Data Vector, where individual variables can be manipulated with data step functions until the end of that iteration of the data step is reached and the record is written to the output file or dataset. This process repeats until the last record has been read from the input dataset and duly processed.

Length 7

link a;

SAS has two different versions of goto !

link and goto statements will both send you to a label elsewhere in the data step, but the difference between them is what happens when you subsequently reach a (possibly implicit) return statement. If you last came from a goto statement, you go back to the start of the implicit data step loop for a new iteration, but if you last came from a link statement, you go back to the statement just after the (most recent) link statement and continue the current iteration.

Although it stops short of explicitly advising programmers not to use these statements, the SAS help file diplomatically points out that

GO TO statements can often be replaced by DO-END and IF-THEN/ELSE programming logic.

Length 8

%let a=;

This creates/overwrites a zero-character macro variable a. It may be local or global, depending on whether the %let statement runs within a macro or in open code. It can be referred to elsewhere in the program as &a. Syntactically, this is not a special case - you never need to use quotes when defining macro variables this way, unless you want to produce a string that contains them! Also, all macro variable values are trimmed when assigned, so inserting whitespace between = and ; has no effect.

Length 9

a="""''";

In a data step, this assigns the value "'' to the variable a. SAS parses the outermost pair of double quotes first, then replaces each inner instance of two consecutive double quotes with a single double quote. The consecutive single quotes are unaffected. The converse happens if you replace the outer double quotes with single quotes.

Strange though it may seem, this functionality can actually be very useful, as it tends to be a lesser evil than using macro quoting functions. Woe betide you should you accidentally try this with an odd number of double quotes, though...

Length 10

%quote(%()

Loosely speaking, the macro processor resolves anything that looks like a macro call (i.e. with a preceding % sign) during compilation, and makes another pass during execution for anything that turns out to be a macro function or variable. Sometimes you need to mask characters that would normally be parsed as macro tokens, or which would otherwise affect compilation. This is one of the most fiddly aspects of SAS.

Depending on precisely what you want to do, SAS has about a dozen different macro quoting functions to choose from, which all behave slightly differently. %quote masks macro characters during macro execution. As demonstrated here, you can also use % characters within certain macro quoting functions to tell the macro processor not to expect a balancing quote or bracket.

Length 11

if first.a;

This is a common data step use case of by-group processing - one of the most distinctive features of SAS. When you use a by statement, SAS uses a system of input buffers to keep track of whether any of the by variables have changed value between iterations. E.g. to use the above snippet, you would need something like by a; first in your data step. Usually, this needs the dataset to be sorted in ascending order.

This snippet is equivalent to if not(first.a) then delete; which under most circumstances means if the current value of a appeared in a previous row, stop this iteration of the data step and don't output the current row.

Length 12

*";*';*);*/;

One of the joys of the SAS Enhanced Editor window - the setting in which one can run SAS code interactively - is that it is quite easy to accidentally submit an incomplete fragment of code for processing. When this happens, SAS will often appear to have stopped responding, usually because it thinks you've left a comment, bracket or quoted string open and is waiting patiently for you to close it. This snippet is an example of a 'magic string' that when submitted enough times may enable you to regain control of your session. Or not.

Length 13

data a/debug;

One largely forgotten component of SAS is the interactive data step debugger. This functions in a similar manner to the MS Office Visual Basic Editor, allowing you to execute iterations of a data step one line at a time and check the values of variables at each point. However, due to the amount of keyboard input required to operate the debugger once you've launched it, it's usually quicker just to modify your data step code so that it prints the equivalent diagnostic information directly to the SAS log.

Length 14

array a{2}(1);

In SAS, arrays are very transient things - merely a way to pick variables from a list numerically rather than by name for the duration of a data step. Once it finishes executing, the variables may still be present somewhere, but the array is gone.

When called in a data step, this snippet creates a numeric array called a containing two elements, which are auto-named a1 and a2. a1 is initialised (to 1) but a2 is not and takes the missing value ..The elements can be referred to as a[i], where i is a numeric variable or constant. Values of the array variables are retained across observations. The elements of a can be referred to as a[i], where i is a numeric variable or constant.

The second set of brackets are required to be round brackets (), but the first set can be replaced with square brackets [] or braces {}. Similarly, you can use any of these when referring to array elements in code.

Length 15

a='01jan1960'd;

We finally have enough characters to show an example of using a SAS date literal. The SAS date epoch is 1st January 1960, so this snippet is equivalent to a=0;. The core SAS language has no concept of data types beyond character and numeric, so even though we've used a date literal there's no way to distinguish between the raw output of these two statements. It's important to note that literals don't behave the same way in the macro language - if you ran something like %let a='01jan1960'd; then the resulting macro variable would be treated as a string until it was evaluated within a core language statement or function.

Length 16

where a=*"John";

Compared to some other languages, SAS has a modest set of operators (perhaps unsurprisingly, given the limited number of types). However, SAS still found space to include one for SOUNDEX matching. When included in a data step or proc, this line restricts the input to records where the variable a sounds like John - e.g. Jane would match. Unlike most other SAS operators, the sounds-like operator is only valid in where clauses, not in more general expressions.

Length 18

input a is8601dt.;

One of the strongest features of SAS is its ability to read data stored in practically any imaginable format with a relatively modest amount of code. The input statement has quite a complex syntax and can be challenging to use, but offers the greatest flexibility when reading in external data out of all the available methods in SAS.

The snippet above uses the built-in is8601dt. datetime informat to read in text of the form YYYY-MM-DDThh:mm:ss from the start of each line of an input file and store it as a numeric SAS datetime variable a. E.g. the text 2014-12-31T23:59:59 would be stored as 1735689599 - the number of seconds since 1st January 1960.

Length 19

proc means noprint;

One curious historical quirk of SAS is that it has ended up with two procs that calculate summary statistics for datasets, with near-identical features and syntax - proc means and proc summary. In early versions of SAS these were distinct procs, but over the decades they've converged to the point where they now share a help page. This example highlights one of the few remaining differences - proc means will output to the listing area by default, unless as here you tell it not to, whereas proc summary doesn't. Although this is a valid SAS statement, it is not a complete call to the proc - at a bare minimum, to request default statistics for the last used dataset, you would need to add a run; afterwards.

Length 20

data a(index=(var));

Another strength of SAS is its ability to crunch through vast volumes of data on disk, without requiring similarly vast amounts of memory - this has historically been one of the main advantages of SAS over R, though in recent years R has been catching up. As with other DBMS software, indexes help tremendously when you only need to extract a small proportion of records. This statement tells SAS to index the variable var when creating the dataset a.

When working with particularly huge datasets, normal SAS indexes can prove inadequate due to their rather generalised design - as a result, people have developed their own more specialised ones.

Length 21

%macro a(b,c=);%mend;

We now have enough characters available to define a trivial macro. In SAS a macro is simply a way of generating text, which is then interpreted as if it were non-macro code. Eventually, anyway - sometimes multiple passes are required to resolve all macro tokens.

Our macro could called like so:

%a(1,c=2);

This would create two local macro variables, with values b=1 and c=2, and then exit, generating no further code. In SAS-speak, b is a positional parameter of %a, and c is a keyword parameter. Positional parameters, when specified, must always go before keyword parameters (and in the correct order) when calling a macro, unless you refer to them by name. E.g.

%a(c=2, b=1); /*Assigns both values as expected*/
%a(c=2);      /*Sets &b to an empty string*/
%a(c=2, 1);   /*Throws an error*/

Length 22

%let a=a;%put &a.&&&a;

This is a highly circuitous method of printing the text aa to the SAS log. The initial %put &a is straightforward enough- this simply resolves &a to its value a. The . tells SAS that it has reached the end of the name of the macro variable, and is not printed. What happens with &&&a is more complex. In the first pass through the code, the macro processor resolves &a to a, its assigned value, and resolves && to &. In the second pass, the macro processor sees only &a and resolves this to a, which is then appended to the a from earlier and printed to the log. If you need to go several layers of variables in, the number of & signs required increases exponentially.

Length 23

proc datasets lib=work;

This has been described as the 'Swiss Army Knife of SAS procs', and with good reason. As well as listing, copying, appending, deleting and renaming SAS files (including, but not limited to, datasets), it can also be used to make all sorts of changes to the metadata within SAS datasets - things like variable names, formats and so on - without having to run a wasteful data step that overwrites the whole dataset. It is among the minority of procs that allow multiple run; groups (as mentioned in example 5), and requires a final quit; statement after the last one. This modest example lists the contents of the temporary work library.

Length 24

dcl hash h(dataset:'a');

Hash objects were first made available in SAS 9.1. The above statement, when run in a data step, declares and instantiates a hash object h containing variables from the dataset a. This is cheating slightly, as some additional statements are required to declare the key variable(s) you want to use to store/retrieve items in the hash, and optionally some data variables associated with each combination of keys. The most common use of hash objects is for merging small datasets onto much larger ones, as using a hash lookup to retrieve values from a small dataset avoids having to sort the other (much larger) dataset.

Length 25

proc format cntlin=a;run;

Before we had hash objects, the next best thing was a format merge. This worked by defining a custom format to translate lookup keys to lookup values, effectively resulting in the lookup dataset being loaded into memory. This snippet takes a specially structured dataset a and uses it to define one or more formats.

Format merges can outperform hash merges if you only need to look up one variable from your lookup dataset, but they have some limitations. A format can only be applied to one variable, so if your lookup depends on a combination of keys, you have to concatenate them - a messy process. Each key can then only be mapped to one value per format, so if you have multiple lookup variables you end up having to load the keys from the lookup dataset into memory multiple times - distinctly sub-optimal for larger lookup datasets.

user3490

Posted 2015-01-19T12:36:59.320

Reputation: 809

1I've been a SAS programmer by title for quite a while now and this is the first time I've seen link. Interesting. – Alex A. – 2015-01-20T15:36:46.750

In my defence, I've never actually used it. – user3490 – 2015-01-20T16:16:02.357

1Nice. Hopefully we get a few more votes so the more fun bits of SAS can be explained. I was pleasantly surprised to find this on the first page :) One fun factoid from me: someone wrote a fully functional (ie, playable) Wolfenstein 3D emulator in SAS a decade or so ago. – Joe – 2015-01-27T23:00:42.843

@Joe: That's incredible! Do you have a link to it or related information? – Alex A. – 2015-01-28T21:19:50.673

1@user3490: It's useful to note that SAS has no concept of data types beyond character and numeric, except in the DS2 and FedSQL procedures, which feature multiple data types. – Alex A. – 2015-01-28T21:20:52.167

1

@Alex http://wolfensas.subshock.net/ . I'm not sure how well it behaves on newer machines/etc., but it used to work at least... it uses SAS to talk to DirectX, I believe.

– Joe – 2015-01-28T21:33:56.467

@Joe: This is absurd. Unfortunately I'm not admin on my work computer (the one that has SAS installed) and I don't think I can justify asking IT to install the font file that's required to play the game... – Alex A. – 2015-01-28T21:41:16.410

@Alex - I'd still say that the core SAS language has no other types. By the way - I've tested wolfensas and can confirm that it still works on 9.x. – user3490 – 2015-01-28T22:27:43.367

The fact that Wolfensas even exists makes me so happy. – Alex A. – 2015-01-28T22:30:27.880

@Joe, I do not think Wolfensas does interacts with DirectX. All graphics seem to just use the SAS window statement and custom fonts. It does interact with several other windows components, but from my quick glance, mostly for the network/multiplayer functionality and I believe tracking the cursor/mouse clicks. I remember finding this years ago and it also made me very happy. – Fried Egg – 2015-06-27T05:27:03.660

I'm very happy to see the "magic string" included. – ConMan – 2016-01-19T06:34:17.260

31

Forth

Forth has only two types, ints and floats (and the floats are optional!) but it still manages to have chars, strings, long long ints, pointers, function pointers, structs, and more; it's all in how you use it!

Length 1

.

The . command (or "word" as we call it) prints out the integer value on top of the data stack; if the stack is empty, you get a runtime error. It also remove the value from the stack — upvote to see how we can keep it!

Length 2

.s

The .s word displays the values currently on the stack, without removing any of them. It also displays the total number of values. In Gforth, .s is limited by default to only showing the top 9 values; maybe we'll find out how to show more?

Length 3

see

Type see followed by any Forth word to see that word's source code. Most Forth words are defined in Forth itself, and only a few primitives are defined in assembly.

Length 4

1 0=

Did I mention that Forth is a stack-based language with postfix operators? Typing 1 0= pushes 1 onto the stack and then executes the 0= word, which pops the top value off the stack and pushes true if it equals 0, false if it doesn't. 0= is a convenience word for 0 =; there are several shorthand words like it for common value+word combinations, like 1+ and 0<>. Moreover, while false in Forth is 0 and any nonzero value is true, the built-in test words return true for true results, and true goes all the way — it's the value with all bits set, i.e., -1!

Length 5

-1 u.

Push -1 onto the stack, then pop it off and print it as an unsigned integer. This can be used to quickly see the maximum value for an unsigned int on your version of Forth (but not the maximum integral value that it natively supports!). You may be asking, "How do we know when an int should be printed with . and when with u.?" Answer: . when it's signed, u. when unsigned. "That's not what I meant," you say. "How do we know when the value on top of the stack is signed and when it's unsigned?" Answer: You're the programmer — that's your job! You have to know whether each integer on the stack represents an int, an unsigned int, an int*, a char*, a function pointer, or other, or else you get the demons in your nose. Forth's not going to keep track of that for you; what is this, C?

Length 6

." Hi"

Prints Hi. ." is a Forth word (which, like all Forth words, must be followed by whitespace or EOF) that reads the input stream up through the next " and prints out any bytes in between. If you put more than one space after the .", all but the space immediately after the ." will be printed. Escape sequences are not supported (so you can't print a string with a " in it with ."), but Gforth adds .\" to the language, which does support them.

Length 7

: + - ;

You define your own words in Forth by writing a colon, the name of the word, the words that you want your word to execute, and a semicolon. A word can be any sequence of non-whitespace characters (whitespace is how Forth tells where one word ends and another begins, after all), even punctuation, and even operators (which are just words, after all). The above snippet redefines + to mean -, so now whenever you try to add, you subtract instead. Any pre-existing words that use + are unaffected, as they store a reference to the original definition of +.

Note: Some words do different things inside definitions of other words than they do outside, but other than control structures, they're all pretty esoteric. Most words do the same thing inside a definition as outside, but sometimes that thing isn't obvious — : show-see see see ; won't do what you think!

Length 8

: 42 - ;

When I said a word could be any sequence of whitespace characters, I meant any sequence. No, Forth does not have a word for each individual number; numbers are just a little special. When Forth encounters a non-whitespace sequence, it first sees if it's a known word; if it's not, it tries to parse it as a number; if that fails, only then do you get an error. Defining a word that's spelled the same as a number means that you won't be able to enter that spelling of the number directly anymore without getting the word instead, but Gforth and various other Forths give you multiple ways to spell numbers anyway.

Length 9

IF 1 THEN

Finally, something familiar! Obviously, this code tests whether its argument 1 is true and, if so, executes whatever's after the THEN, right? Wrong. When execution reaches the IF, the value on top of the stack is popped off, and if that value is true (i.e., nonzero), execution continues with whatever's inside the IF ... THEN and then whatever's after the THEN; if the value is zero, we just skip straight to after THEN. Note that, due to how these words are implemented internally (which is in terms of other Forth words!), IF and THEN can only be used inside a word definition, not in "interpret state."

Length 12

( x y -- y )

This is a comment. It goes from the ( to the next ) immediately after it. (In the interpreter, a newline can also end it.) This is not "built in" to Forth's syntax (Is anything?); ( is just another word, one that discards everything in the input stream up through the next ). (That's right — Forth can manipulate how its source code is read. Perl's not the only language that can't be parsed without executing it!) Since it's a word, you have to follow it with a space, or else Forth will complain that (x is undefined. We can also redefine ( as part of our ongoing campaign of shooting ourselves in the foot.

The comment's content is more interesting, however. This comment specifices the stack effect for some word; the part to the left of the -- lists what should be on the top of the stack before you run the word (the top is on the right), and the right side of the -- describes what the top of the stack will look like afterwards (again, the top is on the right). Common convention is to add such a comment to the source of any word you define, right after the : name bit, and there is also a very strong convention about naming stack elements to indicate their type that is even followed by the standard.

Incidentally, the stack effect shown is for the nip word. You should be able to tell what it does just from the comment.

Length 13

1 2 3 4 d+ d.

As previously indicated, a Forth value's type is all in how you use it — if you treat a value as a pointer, it's a pointer, and if that value's not a good pointer, it's your fault for treating it as one. However, regardless of what type you're treating a value as, it will always take up one cell on the data stack; the exceptions are double cell or double precision integers. These are integers that are represented by two values on the stack, allowing you to perform arithmetic with twice as many bits as usual. The more significant or higher-bit cell is placed on top of the less significant or lower-bit one, so that 1 0 is the double cell representation of 1, and 0 1 is either 2^32 or 2^64, depending on how big your Forth's regular cells are. Naturally, in order to treat a double-cell value as such, we need to use words that explicitly operate on double-cell values; these are generally just d (or ud for unsigned) followed by the name of the corresponding single-cell word: d+ for addition, d< for comparison, d. for printing, etc.

jwodder

Posted 2015-01-19T12:36:59.320

Reputation: 469

+1 for Forth. I was starting to look for languages that hadn't been done yet. Happy to see it here already. – mbomb007 – 2015-01-20T19:33:43.560

2Also, if you ever get to +1675, I've got a nice ASCII image to output. :D – mbomb007 – 2015-01-20T19:39:55.893

30

IBM Enterprise COBOL

Factoid: Whilst it is possible (twists and turns) to have a useful two-character program (to be the target of a CALL to a sub-program which doesn't otherwise exist yet), other than variations of the same thing, the next one would come in at 26 characters, and would be a variation which... doesn't work.

Plus that is not counting the mandatory seven blanks at the start of a line. And it would be severely abusing the language.

COBOL's not really so good for this challenge.

This is becoming interesting in itself. Although it will be a while before I can get the program to do something else, it is an interesting academic voyage of discovery.

Remembering that these are short, and abused, programs it is interesting that only valid COBOL can be ignored, if invalid it gets an S-level diagnostic, which is going too far. Some actually valid COBOL will not work without a full-stop/period, as I've noticed when trying to Golf(!) things previously.

Two characters

Excellent. Here's the two-character example. Remembering, sorry about that, that it must be preceded by seven blanks.

   ID

Doesn't look like much of a program. Certainly not much of a COBOL program. You do have to bend things a little.

Compile it, and these are the diagnostic messages you get:

 1  IGYDS1102-E   Expected "DIVISION", but found "END OF PROGRAM".
 "DIVISION" was assumed before "END OF PROGRAM". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

                  Same message on line:      1 

 1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
 Program-name "CBLNAM01" was assumed. 

That gets you a Return Code/Condition Code of eight. Normally you wouldn't generate the code for, or attempt to execute, a program with an RC/CC higher than four. However, none of those messages affect the generated code (except the allocation of a Program-name).

What does the program do? When it is CALLed, it simply returns to where it was called from, in the normal manner.

How would you use it?

Whilst developing a program, you want to check out the control flow, but you haven't written a couple of the sub-programs yet. Simply copy the loadmodule (created by feeding the object code produced into the linkeditor/binder) to the name of the CALLed program and, assuming you are using Dynamic CALLs, you have a stub which is just going to give you back control. For a Dynamically-called program, the PROGRAM-ID (Program-name) is irrelevant, so it does not matter if you accept the generated name.

An equivalent "real" program would be this.

   ID DIVISION. 
   PROGRAM-ID. Anything.

Alternate two-character (didn't know about this before)

   FD

Diagnostics

    IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found 
    in this program.  It was assumed present. 

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

Note the lack of line-number for the first two messages. This time, with an ID, there is no line-number to associate those messages with.

Three characters also didn't know

    1 A

Diagnostics

    IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found 
    in this program.  It was assumed present. 

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

This program defines a group-item (valid for this purpose) but it is discarded.

Program operates as above.

Four characters

Since it is COBOL, we should see a full-stop/period at some time. Now.

   1 A.

Even though the line is discarded, it gets one less diagnostic because the program source now ends with a full-stop/period.

Five characters

We're up to five votes, so here's a five character program that is equivalent:

   ID FD

This operates in exactly the same way as the two-character example. FD is valid COBOL, so the compiler realises there is some stuff missing. Without it being valid COBOL, there would be an S-level message, and an RC/CC of 12. With it being a valid COBOL word, but obviously out of place, the third messages shows that it is just ignored.

 1  IGYDS1102-E   Expected "DIVISION", but found "FD".  "DIVISION" 
 was assumed before "FD". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "FD". 

 1  IGYDS1022-E   A data-name or file-name definition was found 
                  outside of the "DATA DIVISION".  Scanning was 
                  resumed at the next area "A" item or the start of
                  the next entry. 

 1  IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
 Program-name "CBLNAM01" was assumed. 

 1  IGYSC1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

Six characters

   ID 1 A

Combining a two character and a three characters, which need to be separated.

Diagnostics similar to the five-character solution.

Seven characters

   LINKAGE

That's a reserved-word used (followed by the word SECTION) to identify the data-items which are defined elsewhere and whose addresses are made available by a CALL from another program. Its inclusion doesn't affect our existing program :-)

Diagnostics

    IGYDS1003-E   A "PROGRAM-ID" paragraph was not found. 
    Program-name "CBLNAM01" was assumed. 

 1  IGYDS1000-E   A "IDENTIFICATION DIVISION" header was not found
 in this program.  It was assumed present. 

 1  IGYDS1005-E   The "DATA DIVISION" header was not found.  A 
 "DATA DIVISION" header was assumed before "LINKAGE". 

 1  IGYDS1103-E   Expected "SECTION", but found "END OF PROGRAM". 
 "SECTION" was assumed before "END OF PROGRAM". 

 1  IGYDS1082-E   A period was required.  A period was assumed 
 before "END OF PROGRAM". 

                  Same message on line:      1 

A little more interesting this time. That "Same message on line: 1" looks odd (as the other message it is the same as is also line 1) but that is because we only have a one-line program and there are two required full-stops/periods (should be one after the SECTION which isn't there and one to end the source program).

Bill Woodger

Posted 2015-01-19T12:36:59.320

Reputation: 1 391

Needs more votes to show the true characteristics of COBOL. – idrougge – 2017-03-12T03:22:58.513

"the next one would come in at 26 characters" and we have 30 votes. What now? – Jerry Jeremiah – 2018-02-07T00:33:08.583

30

Scala

Scala is a JVM-based, statically-typed (mostly), hybrid functional/object-oriented language, with type inference, higher kinded types, and generics.

Factoid: Scala started with the man behind Java generics and a lot of the Java compiler, Martin Odersky.

1

Snippet

;

Explanation

There isn't much need for semicolons in Scala (unlike its cousin, Java), but they can still be found in some places, such as for statements (also known as "for comprehensions"). For example:

for (i <- 0 to 10;
     a <- 0 to 10
) yield (i, a)

Will return a list going something like (0, 0), (0, 1)... (1, 9), (2, 0)... (10, 10).

2

Snippet

()

Explanation

Scala's Unit type has only one value: (). Used like Java or C's void. Don't be fooled, though: it's not an empty tuple! This type is mostly returned from functions with side effects, to distinguish them from the purely functional ones. In Scala, every function must return a value. If they don't, they implicitly return ().

3

Snippet

???

Explanation

An operator which just throws NotImplementedError. Luckily, thanks to Scala's powerful type system, it can be put in any unimplemented function and still be typesafe:

def notImplemented: Int = ???
def foo: String = ???

One of the best parts of Scala is that there's very little baked-in as compiler magic, and you can write most of the builtins yourself. Operators are simply functions with names that contain symbols - ??? itself can be defined as:

def ???: Nothing = throw new NotImplementedError("an implementation is missing");

4

Snippet

None

Explanation

While Scala does have null as part of the language (as an unfortunate holdover from Java), it also has a pre-made option type, called Option[T]. If an optional value isn't there, its value is None. If a value is optional, make it an Option, and you won't ever have a NullPointerException. You can also implement Option yourself, like so:

sealed trait Option[+T]
case class Some[T](value: T) extends Option[T]
case object None extends Option[Nothing]

5

Snippet

(1,2)

Explanation

A 2-tuple (a pair) of integers, 1 and 2. Especially useful for returning multiple values from functions, as well as pattern matching. Observe:

def printPoint(p: (Int, Int)) = p match {
    case (x, y) => println("X coordinate: " + x + ", Y coordinate: " + y)
}
printPoint((1,2))
// prints "X coordinate: 1, Y coordinate: 2"

6

Snippet

()=>()

Explanation

An anonymous function. As a functional language, Scala has first-class language support for anonymous functions. To dissect this snippet, it's a function which:

() - Takes no parameters,

=> - And returns...

() - Unit!

7

Snippet

s""""""

Explanation

The empty string... with a twist. If you begin and end a string with triple-quotes, you can include unescaped characters inside. For example:

"""

"""

Is equivalent to:

"\n"

Also, a string beginning with s can have interpolated values in it. For example:

val num = 10    
val str = s"There are $num nums"
// str == "There are 10 nums"

It gets better though: with braces, you can put expressions inside!

val str = s"2 + 2 == ${2 + 2}."
// str == "2 + 2 == 4."

8

Snippet

Future{}

Explanation

Futures are things that will happen or be computed... sometime later. Scala has a lot of different models of concurrency that are each useful in their own way (like the Akka framework), and Futures are one of them. Future{} computes (). Pretty useless, but if I have something really expensive to do, like compute 2 + 2 and multiply that by 5, they're pretty handy:

Future {2 + 2} map {_ * 5)

They're also great for I/O. Admittedly, you have to do a couple of imports for this, but they're in the standard library.

10

Snippet

type N=Int

Explanation

This is a type variable called N, which refers to the type Int. You could now write:

val num: N = 1

And it would work.

Addendum: I said type "variable", but these can't vary during runtime. You can use these for some nifty type-level programming like the Heterogeneous List, or HList, which is a List that contain several different types of elements while still being typesafe. If you're interested, watch Daniel Spiewak's "High Wizardry in the Land of Scala": http://vimeo.com/28793245.

16

Snippet

implicit val a=1 

Explanation

Have you ever used a heavyweight dependency injection framework like Guice or Spring? If so, you know that dependency injection is (in essence) supplying objects with their dependencies at construction, so that they can stay loosely coupled. The issue with doing this the easy way is that constructor signatures quickly grow out of control when you start to build large dependency graphs. To fix that, you bring in a DI framework, and soon after, your project has 50k lines of XML. :-(

Now for a seemingly unrelated question: have you ever needed to call a series of functions, all sharing a few parameters? Has that ever become so cluttered that you added an extra class, just to put the parameters in one place?

Implicits give you a way to inject a value of a particular type in a particular scope into a function call. This way, functions can ask for a value without you needing to explicitly provide it. It's filled in automatically! One of the best parts, and the reason this relates to DI, is that constructors also work with implicits. You can create huge parameter lists in your constructors to keep them loosely coupled, but users of your classes will never have to supply all of the parameters manually (but they can, if they want).

This particular snippet creates an implicit value of type Int in the current scope, with the value of 1. If any function calls require an implicit Int, they'll automatically be fed 1.

Schalat

Posted 2015-01-19T12:36:59.320

Reputation: 373

Excellent tips, please keep them coming. – Utku Özdemir – 2015-07-17T16:16:02.593

2snippet 17 suggestion: (x:{def f:T})⇒x.f. "duck typing". you can have a function receive anything that has a method f which returns a T. could be used as poor man's polymorphism. if you have classes from 3rd party library, which expose a method foo: Bar, and you want to treat these classes the same way you treat your own classes which expose the same API (i.e. foo:Bar), but don't have a suitable interface to inherit from, you can use this syntax. – gilad hoch – 2015-07-20T06:27:26.247

30

Ruby

Ruby is a dynamic, reflective, object-oriented, general-purpose programming language. It was designed and developed in the mid-1990s by Yukihiro "Matz" Matsumoto in Japan.

Link for myself, or anyone who wants to contribute to this answer.

Length 19 (by a guest)

[1, 2].each{|i|p i}

Ruby supports for loops, but the .each method is preferred. The code in brackets is a block, essentially a single-use anonymous function. Blocks can take parameters, which are enclosed in pipe characters. The p is a shortcut for puts [something].inspect. The .inspect method is a variation of .to_s which provides more details about the object.

Length 18

%i[I love you too]

This is an example on how to create an array of symbols, the result would be: [:I, :love, :you, :too]

Length 17

'1.34'[/(\.\d+)/]

This is an example on creating snippet then parse it using regular expression. This regular expression means get any dot \. that followed by one or more (+) digit (\d) then capture it. The result of this snippet is a new string containing .34.

Length 16

'abcdefg'[3..-1]

This statement means, create a string containing abcdefg, then get the fourth (4th = 3) character until the end (last = -1). Another example: [3..3] get the fourth character only (d), [3..5] get the fourth until sixth characters (def), [-3..-1] get the third last character until the last character (efg).

Length 15

%w{i love you!}

This is a shortcut to create array of words (string), that is equal to ['i', 'love', 'you!']

Length 14

[1,2,3,4]*'ab'

Array multiplication with a string equals to call a .join method, the result of this snippet is 1ab2ab3ab4, that also equal to calling: [1,2,3,4].join 'ab'

Length 13

y=->x{x**3}

This is an example on how to create a lambda (or sometimes called anonymous function) using stab operator ->. This statement means create an anonymous function that accept one parameter x that returns x*x*x, then assign this function to a variable named y. Any lambda can be called using .call method, for example:

y = ->(x){x**3}
y.call 8 # 512

This is equal to:

y = lambda {|x| x**3}

Length 12 (by Devon Parsons)

puts "#{$$}"

This snippet shows a couple things. As shown below, puts writes to STDOUT. Code encapsulated in #{ code_here } is evaluated when the string is created, provided the string is made with double quotes. And ruby stores a bunch of useful global variables in double-character shorthand: For example, $~ is the most recent regex match, and in this snippet, $$ is the current process ID. So this snippet writes the current process' ID to STDOUT.

Coincidentally, the ID is of type Fixnum. The string interpolation automatically calls the to_s method on the evaluated code, and to_s by convention returns a string interpretation of the object.

Length 11

x={a:1,b:2}

The statement above is one (of many way to create a Hash or commonly called associative array), to access the value, you can type x[:a], where :a is a symbol (explained in Length 2). To set a value you can type x[:key_name] = 'yayy'. The key of a Hash could be anything not just symbol. Another popular way to create a Hash is using => symbol, for example:

x = { 'a' => 123, 456 => [7,8,9], c: 'wow' }
# x['a'] == 123
# x[456] == [7,8,9]
# x[:c] == 'wow'

Length 10

[*(8..11)]

In this snippet, that statement has the same effect as typing: [8,9,10,11]. The 8..11 part is called Range object. The * operator is the splat operator, in this part, the operator has the same effect as .to_a to array conversion (8..11).to_a.

Length 9

def x;end

This is an example on how to create a function, that example is the same as:

def x
end

To fill the function content, you may type it before the end keyword, for example:

def x
  puts 'the x function has been called'
  123
end

Anything that typed before end keyword would be returned, so in this statement y = x, the y variable would contain 123.

Length 8

9.to_s(2)

This is an example on how to perform base conversion from base-10 integer to binary number, the result would be 1001. You can change number 2 into another base, and .to_i can have parameters too, to parse from string to number, for example '1101'.to_i(2) that would return 13.

Length 7

__END__

__END__ is a line keyword that denotes the end of regular source code, the lines below that line wont be executed and would be gathered in DATA string constant.

Length 6

rescue

The rescue keyword is Ruby's keyword to catch raised exception, we could use this as one-line, for example: x = 1/0 rescue 2, that would set x into 2, or we could use it within begin and end keyword, for example:

begin
  1/0
rescue ZeroDivisionError
  puts 'zero division detected
end

You can find more information about ZeroDivisionError here.

Length 5

BEGIN

BEGIN is a keyword that will execute following code-block before anything else withint the script, for example puts 'b'; BEGIN { puts 'a' } would give an output: a then b. There are also END keyword that executes next code-block before program termination.

Length 4

puts

This function would print a newline on the console, if you add anything as parameter for example: puts('A') or puts 'A', this would print an A character then a newline.

Length 3

'A'

Single quote is one way to create a string, there are another way such as double quote, always use single quote for better performance when no interpolation needed. To get the code-point value of a single string, use .ord method.

Length 2

:x

This is an example on how to create a symbol. Symbol starts with colon followed by quoted string, underscore or alphabet. Symbol is an object to hold immutable string, that normally used as hash's key. To convert it to string, use .to_s method.

Length 1

1

This is an example on how you make a Fixnum object, fixed number is an integer. everything is an object in Ruby, they could have methods such as: 1.to_f would return 1.0 a Float object, or 1.to_s would return "1" a String object.

Factoid

Gems is Ruby's package (library and programs) manager.

Kokizzu

Posted 2015-01-19T12:36:59.320

Reputation: 1 531

Kokizzu, why did you add so many snippets? You are only up to 13 votes – Devon Parsons – 2015-02-18T14:33:30.133

overexcited.. XD – Kokizzu – 2015-02-18T15:41:24.253

Should be rolled back now that it's past 20! – fede s. – 2016-03-24T00:32:41.533

Ruby has so many awesome features! Why have I never bothered to learn to use it? – ETHproductions – 2016-11-14T05:05:15.317

@ETHproductions I have no idea why Python was chosen over it as a learning language. Ruby is simpler at first and much more powerful after you learn the basics. – dkudriavtsev – 2016-11-14T05:36:24.003

30

Perl

Factoid: Though people occasionally stylize Perl as "PERL," it is in fact not an acronym.

Note: This has been relinquished to the community as a wiki. Please feel free to add snippets as you see fit, but please try to retain the formatting used for snippets 1-6 since it looks so clean. :)


Length 27

sub{ $_=shift; lc }->('SE')

An anonymous subroutine: that is, one with no name. This one is followed immediately by ->(...) for its arguments. This snippet also demonstrates a number of other features:

(1) shift acts on an array, lopping off the initial element and returning it; (2) @_ is the array holding all the arguments passed to a subroutine; (3) shift with no arguments, in a subroutine, acts on @_. Thus, the first statement in our subroutine assigns to the variable $_ the first argument passed to the subroutine, in this case 'SE'.

(4) lc returns the lowercasified version of a string (without changing the original variable if the argument is a variable); (5) lc with no arguments acts on $_. Thus, here, lc acts on $_ which is 'SE' and returns 'se'.

(6) If you reach the end of a subroutine (and thus haven't yet returned anything), the subroutine returns the return value of its last statement, if any. Thus, in this case, the subroutine returns 'se'.

Note: Many of these features are very useful in code golf; in real life, for clarity's sake, you will often want to specify the arguments to functions rather than relying on default arguments like $_, and to specify return values of subroutines rather than relying on the return value of the last statement (especially if the last statement is complex).


Length 26

join '', split /\W/, $foo;

This demonstrates using a function (with its arguments, or a unary operator) as an argument to another function or unary operator. When, as here, the first function is the final parameter of the other, you usually don't need parentheses to disambiguate. They may be useful for clarity in some cases, but the join... split... construct is so well-known that you don't need parentheses here.

split takes two arguments. (Well, it can take zero to three, but it takes two in this case.) It splits the string $foo along demarcations matching the regular expression /\W/, and its return value is a list of the remaining substrings. join puts those back together with the empty string between them. (Incidentally, $foo =~ s/\W//g is a simpler way to accomplish the same thing.)


Length 25

sub foo {
    return 1;
}

Our first subroutine! In a later snippet, we'll see how to use arguments (parameters) passed to a subroutine; for now, our subroutine just returns 1 back to whatever called it. Our subroutine is called foo; anonymous subroutines are also possible and will be covered in a later snippet.


Length 24

my $has_nums = $x=~/\d+/

See the length-23 snippet. Like that one, this, too, binds $x to a regular expression, and almost the same one. (Like /(\d+)/, it looks for a string of digits.) But this one is being assigned to $has_nums rather than to a list, so it's being called in scalar context. The binding operator =~ in scalar context, when the right-hand side is /.../, returns 1 (which is true) or the empty string (which is false) depending on whether the match succeeds. So now you can use $has_nums in if $has_nums, for example. (What =~ returns in scalar context is different if its right-hand side is s/.../.../ or some other things.)


Length 23

my ($num) = $x=~/(\d+)/

This demonstrates =~, called the binding operator. It binds (in this case) $x to the regular expression /(\d+)/. Like just about everything in Perl, this operator returns something, and what it returns depends on what context it's called in. Assigning the binding operator's return to a list ($num) is calling it in list context. The binding operator in list context, when it's binding to just a regular expression /.../, returns the list of matches to the stuff in parentheses in the regular expression, which in this case is \d+, a string of digits. So $num is assigned to the first string of digits within $x. (What =~ returns in list context is different if its right-hand side is /.../g or s/.../.../ or other things.) See also the length-24 snippet.


Length 22

$x = 1==0 ? 'a' : 'b';

... ? ... : ... is the ternary operator. It has precedence over comparison operators like == but not over assignment operators like =, so the above means the same as $x = ( (1==0) ? 'a' : 'b').


Length 21

if ($x) {
    # ...
}

This demonstrates Perl comments, which are from # to the end of the line, and the common practice of indenting four spaces for clarity. (There are other ways to comment, too, but those will have to wait for a later snippet. This snippet also tests $x for truthiness, but truthiness, too, will have to wait.)


Length 20

next LBL if $x >= 0;

This demonstrates Perl's use of postfix if. (It means the same as if ($x >= 0) {next LBL;}.) Postfix control-flow statements are usually (outside of golfing) reserved for things like next and last and warn and die where the point of postfixing is to draw attention to the crucial command being conditionally executed.


Length 19

$_ = 'quux';
print;

This demonstrates Perl's use of a default input for (many) built-in functions. If you don't say what you want to print (or lcfirst or sqrt or split or…), Perl will do it to $_. (The same is true for binding to a pattern match, and $_ is the default scalar used in other circumstances also — but those will have to wait for a later snippet.) For clarity and to ensure you're using the variable you think you're using, it's often best to use some variable other than $_.


Length 18

@hsh{'Ann', 'Bob'}

This is a hash slice. As in the Length 17 note, below, the {...} (rather than [...]) signifies that %hsh is a hash. And the @ sigil here signifies we're making a list of our hash values. Which hash values? The ones with the keys listed. So if %hsh is ('Ann' => 123, 'Bob' => 345, 'Cam' => 567) then @hsh{'Ann', 'Bob'} is (123, 345).


Length 17

$ary[0] = $hsh{a}

$ is the sigil for a scalar. But an element of an array, or a value of a hash, is a scalar. So even though may call an array @ary and a hash %hsh, their values are $ary[...] and $hsh{...}. The type of bracket indicates whether it's an array or a hash.


Length 10

print$x=<>

This is a “one-line cat” program: it outputs one line of its input, then exits. It demonstrates several features of the language. The null filehandle is used again, now to assign a line of input to the variable $x. This assignment also returns the value, which is then printed to STDOUT. But wait! Didn't <> return the whole file in Snippet 7, not just one line? Perl statements know about the “context” they're evaluated in. In “scalar context”, <> reads one line. In “list context” it reads (“slurps”) the whole file at once; the result is a list with one element for each line. print provides a list context (and concatenates its argument list), but assignment to the scalar variable $x enforces scalar context.


Length 7:

print<>

This, like cat, prints back its input. The <> is the “null filehandle”; its lack of a name means that it reads from the “magical” filehandle ARGV, which sequentially opens and reads from filenames given as line arguments, or STDIN if there are no arguments (just like cat does). In the full form, the filehandle goes between the angle brackets: <FILEHANDLE> may also be spelled readline(*FILEHANDLE).


Length 6:

Int $x

Perl 5 is all dynamic typing. But Perl 6 supports both static and dynamic typing! It's one of the many ways in which the two versions have diverged.


Length 5:

'$x'

This may seem trivial but it's something that can confuse people new to Perl who are familiar with other languages. In some languages, it doesn't matter whether you use single or double quotes. It does in Perl, though. If you have a variable $x equal to 5, "$x" returns "5" and '$x' returns '$x'. Perl interprets things in double quotes but uses anything in single quotes literally.


Length 4:

less

The Perl pragma to use less of something, available in CPAN. Examples include use less 'fat'; for those on a diet, or use less 'CPU'; for those whose computers are on diets. The class method less->of('x') will tell you if use less 'x'; was specified. Unless you take advantage of that class method in some way, specifying use less is useless. (See what I did there?)


Length 3:

use

Perl is extensible via modules, which are loaded using use. Other things use use too. Show self-discipline; use strict; use warnings; in your programs.


Length 2:

$!

Oh no, something has gone wrong! The program has died, be it intentionally (via die) or by the will of Zeus. But why oh why has execution stopped? At last, $! rides the Perl camel to the rescue. It contains the error code. (There's also $@, which contains the error message.)


Length 1:

;

Like so many other 1 character answers here, ; is a valid Perl statement which does nothing. On its own it's about as useful as vacuuming a block of tofu.

Alex A.

Posted 2015-01-19T12:36:59.320

Reputation: 23 761

It seems snippet 10 isn't really a cat. With perl 5.18, at least, it prints only one line. To echo all the input, one could write e.g. print(<>); (which is ten characters long) or print $x=<> until eof (which is slightly smarter). – xebtl – 2015-05-11T19:56:27.623

@xebtl: I think it was PhiNotPi who did snippet 10. I made this a community wiki so go ahead and make changes as you see fit. :) – Alex A. – 2015-05-11T20:07:17.920

How about this? If it is too repetitive, we can delete Snippet 7 again. Perl is so full of features worth showcasing! – xebtl – 2015-05-11T21:02:11.093

@xebtl: Looks good to me. Note that some features not covered here may already be covered by ASCIIThenANSI's Perl submission. – Alex A. – 2015-05-11T21:04:16.147

@ASCIIThenANSI: If you have more to share that you didn't cover in your Perl answer, you're welcome to contribute to this community wiki. – Alex A. – 2015-05-11T23:30:07.770

Fun Fact: Snippet 5 also applies to PHP ;) – brianush1 – 2016-07-11T19:19:04.340

30

Rust

Rust is a general purpose, multi-paradigm, compiled programming language developed by Mozilla Research. It is designed to be a "safe, concurrent, and fast."

Link for myself, or anyone who wants to contribute to this answer.

These snippets are subject to change, since Rust syntax are not yet stable. Please give a comment when there are things that no longer work on latest Rust.

Length 75

fn a<T:Default>(v: T,p:&Display) -> T { println!("{:?}",p); T::default() }

For any Type that implements T (the default trait) and that calls function a in your code, the compiler will create a dedicated function that only that type will call and use. This is called monomorphization.

At the same time, all these new functions accept a value p, as a fat pointer (A pointer to the value, and the display implementation of that value).

These new functions can display the value p by dynamic dispatch (invoked by println!).

Length 9

fn main()

The main() function is the main function. Here's the example of hello world

fn main() { println!("hello world"); }

If saved as hello.rs, the source can be compiled and run using this command:

rustc hello.rs && ./hello

Length 8

fn x(){}

This is an example on how to create a function named x. The arguments can be written inside (), the statements or expressions can be written inside {}, and the return type can be written between ){ sign, for example:

fn x(a:i32, b:i32) -> i32 {
  if a == 0 { return b; }
  a + b // equal to return a+b;
}

The return keyword used to exit the function. Just like Ruby, the last expression in the end of the program will be returned when return statement not visited at runtime. Here's the exact same function without return keyword:

fn x(a:i32, b:i32) -> i32 {
  if a == 0 { b } else { a + b }
}

Length 7

if x {}

This is the if syntax of rust, this part similar to Go's if syntax. We could also write like this:

let y = if z == 3 { 9 } else if z > 3 { 12 } else { 15 };

Length 6

print!

The print! and println! is the standard output function. This function has similar syntax to .NET's String.Format method. Here's some example:

print!("{0} {1} {0}",123,234);     // 123 234 123
println!("{} {} {}",123,234,345);  // 123 234 345
print!("{a} {b} {c}",a=1,c=2,b=3); // 1 3 2

The {} symbol are called next argument specifier, {number} is positional parameter, and {string} is named parameter, we could mix any of them. To print the type of a value, you can use :? debug traits, see this link for another formatting traits.

println!("{:?}", 123 );
// 123i32

println!("{:?}", "abc" );
// "abc"

println!("{:?}", std::io::stdin().read_line() );
// some possible outcomes:
//  Ok("string that has been read\n")
//  Err(IoError { kind: EndOfFile, desc: "end of file", detail: None })

println!("{:?}", std::io::stdin().read_line().ok() );
// some possible outcomes:
//  Some("string that has been read\n")
//  None

println!("{:?}", std::io::stdin().read_line().ok().expect("Fatal: read_line failed!") );
// some possible outcomes:
//  "string that has been read\n"
//  thread '<main>' panicked at 'Fatal: read_line failed!', /build/rust/src/rustc-1.0.0-alpha/src/libcore/option.rs:330 
//  ^ this one not entering the println! function

Length 5

stdin

The stdin is a function that could access the standard input (when called, it returns a std::io::stdio::StdinReader type), usage example:

let s = std::io::stdin().read_line().ok().expect("Fatal: read_line failed!");

Or we may type:

use std::io::stdin; // outside function
let s = stdin().read_line().ok()
               .expect("Fatal: read_line failed!");

The .ok() part would check if read_line failed and the .expect("Fatal: read_line failed!") part would exit the program when it does.

Length 4

true

Just like common programming languages, this is a constant with type bool. As you can guess, the other value named false. There are another primitive type in Rust, for example char (32-bit unicode), that can be initialized using single quote. To convert char to string, use .to_string() method.

Length 3

let

The let keyword is the keyword to declare a variable, here's some example on how to use it:

let x = 1;
let (y, z) = (3, 4);
let a : u64 = 18446744073709551610;

The variable defined by let keyword are immutable, to make it mutable, add mut keyword, for example:

let mut b = 123;
b = 234;   

Length 2

""

This is an example on how to create an empty string slices (slice of u8) or &str. This string saved on the program's binary, and cannot be mutated/deleted within runtime. There are another type of string in Rust, a mutable one, that called String. To convert between &str and String use .to_string() method, that copies the old string into another place so it can be modified (mutated). To convert String to &str, use .as_slice() method.

Length 1

1

This an example of valid number literal, to force it as unsigned add a suffix u or _u (uint), some other suffix exists such as i (int), u8, i8, u16, i16, u32, i32, u64, i64, f, f32, and f64.

Factoid

Rust has certain design philosophy:

  • Memory safety must never be compromised
  • Abstraction should be zero-cost, while still maintaining safety
  • Practicality is key

Kokizzu

Posted 2015-01-19T12:36:59.320

Reputation: 1 531

1Tell me more... in, er, 2 characters..? – Phil H – 2015-01-27T11:00:54.500

that's hard.. XD lemme study first in 5 minutes.. – Kokizzu – 2015-01-27T11:01:23.067

I don't know if this could persist for a long time http://codebunk.com/b/55619431/ for backup: http://pastie.org/9865143

– Kokizzu – 2015-01-27T11:20:22.357

1This is the first time I've heard about Rust. +1 for luring me in. Looking forward to seeing more. – Alex A. – 2015-01-27T19:33:02.943

@Kokizzu CodeBunk persists for a long long time – spicavigo – 2015-04-08T23:06:52.540

too bad I'm no longer interested in Rust. Go ftw! – Kokizzu – 2015-04-09T06:37:58.073

29

F#

F# is a strongly typed, multi-paradigm programming language that encompasses functional, imperative, and object-oriented programming techniques.

All the snippets included here can be run online at: http://www.tryfsharp.org/Learn (exception: FSI snippet).

Length 9 Snippet

(10, "Z")

Tuples! a Tuple is defined as a comma separated collection of values. While Lists (and Arrays) gravitate towards the concept of a Set, Tuples are more like a data structure that groups related values.

The snippet defines a 2-tuple. One value is integer, the other string. F# annotates the type as: int * string

Tuples are considered ad hoc types, so they are passed as a single argument, can be a return type and so on.

F# has two built in functions to help with tuples: fst and snd that return the first or second element of a Tuple respectively. Tuples are not limited to just two elements, though.

Length 8 Snippet

[-9..10]

F# allows to define ranges of sequential values. This snippet generates a list of 20 integer elements, -9 and 10 inclusive.

You can define stepping values, for example [0..10..50] will yield a list of 6 elements: [0; 10; 20; 30; 40; 50].

The range syntax is the same for lists and arrays.

Length 7 Snippet

let a=1

We can now define values. Values in F# are immutable by default, that is the reason we avoid the use of the term "variable".

The snippet defines an immutable value "a" that contains a 1 (integer).

Length 6 Snippet

2.**8.

Now we can use the Power function.

Note that I could not call the Power function before with arguments "2" and "8", because [the arguments] would be considered integers. The decimal points make the compiler to infer a floating point number. This snippet correctly returns a 256.0 (float) value.

Floats in F# are double precision.

Length 5 Snippet

[|0|]

At five characters, we can define an array with one element (as mentioned before, the compiler infers the type to int[]).

Not to be confused with a list. An empty list is defined simply by the square brackets like this: []

The element separator, in both lists and arrays, is the semicolon (;) as in [| 1;2;3 |]

Length 4 Snippet

(**)

It's not an emoticon, it is a multi-line comment in F#. For some odd reason I didn't find this syntax intuitive. I got used to it until much later.

Single-line comments are double-slash (//), just like C++, C#, Java, etc.

Length 3 Snippet

nan

Three characters unlocks many basic arithmetic operations (1+2, 9*9 and so on). But I picked nan. It is a shortcut function that simply returns System.Double.NaN.

Useful to compare (or match) the result of a function.

Length 2 Snippet

;;

I could've used an empty string ("") as the snippet. That would create a function that returns an empty string, but it is the same concept as the length 1 snippet.

Instead, I picked the empty statement in F# Interactive (FSI). FSI is a REPL tool that allows you to declare, construct and otherwise experiment with your code in an interactive manner and it is very useful. In my opinion, the ;; is used more frequently than empty strings.

You must append double semicolons (;;) at the end of your statements in FSI to indicate the end of input.

Length 1 Snippet

0

A function that returns zero (the compiler infers the type to integer). Commonly used as the final statement to return the program exit code.

Factoid: F# uses type inference. The programmer does not need to declare types - the compiler deduces types during compilation.

Mike Rod

Posted 2015-01-19T12:36:59.320

Reputation: 393

Just FYI: Mathematica has the same syntax for multiline comments so it's not all that foreign. :) – Alex A. – 2015-04-06T21:28:20.727

29

PHP

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. As of January 2013, PHP was installed on more than 240 million websites (39% of those sampled) and 2.1 million web servers. Originally created by Rasmus Lerdorf in 1994, the reference implementation of PHP (powered by the Zend Engine) is now produced by The PHP Group. While PHP originally stood for Personal Home Page, it now stands for PHP: Hypertext Preprocessor, which is a recursive backronym.

Link for myself, or anyone who wants to contribute to this answer.

Length 16

The function

http_build_query

builds a query string for an URI from an associative array.
One of many functions that´s closely connected to web development.

Length 15

array_intersect

This function returns the common elements of two or more arrays.

Array function names in PHP are bulky. Apart from implode and explode (respectively join and split), they are almost always prefixed.

Length 14

imagefilledarc

Since version 4.0.6, php has builtin image processing with some pretty sophisticated functions. imagefilledarc is one of them. It can be used e.g. for painting a three dimensional pie chart.

Length 13

if($a >= $b):

This is the alternative syntax for control structures, which ends when it finds a endif; statement. This syntax can be used with if, while, for, foreach, and switch, and end with endif; endwhile; endfor; endforeach; or endswitch; respectively. This alternative syntax is most used to output html without echoing html tags:

<?php foreach($items as $item): ?>
<p><?php echo $item; ?></p>
<?php endforeach; ?>

Length 12

function(){}

This is an example of anonymous function, that can be assigned to a variable, or passed as parameter, for example:

$cmp = function($a,$b) {
  if($a<$b) return -1;
  if($a>$b) return 1;
  return 0;
};
$arr = array(3,1,2);
usort($arr,$cmp);
print_r($arr); // array( [0] => 1, [1] => 2, [2] => 3 )

Length 11

['a'=>[12]]

This statement is equal to array('a'=>array(12)), this short array syntax available since PHP 5.4.

Length 10

$a=array()

This is an example on how to create an array, don't forget to add ; at the end of the statement. The array will have empty length, you can check it using sizeof function. To append at the end of that array, you might use []= operator, for example: $a[] = 12, this would append a number 12 to that array, that similar as typing array(12) at initialization.

Length 9

phpinfo()

This function will print all information about current configuration and variables on your system.

Length 8

__FILE__

Magic constant __FILE__ is a constant that have different value depends on the file its being declared, there are also __LINE__ that shows the line number where its being declared, and __FUNCTION__ for function, __DIR__ for directories (since PHP 5.3). You could see the full list here. They could be used as better way to implement includes, for example: include dirname(__FILE__).'/file.php'; or include __DIR__.'/file.php';, credits: @ismael-miguel

Length 7

4**3**2

Exponentiation operator ** is supported since PHP 5.6, the result of that execution is 262144 (from 4**9)

Length 6

$_POST

This is a global variable that holds value from HTTP protocol with method POST, for example, if you have this form: <form method='post'><input type='submit' name='a' value='b' /></form>', when that button clicked, the current PHP script could access the submitted value using $_POST['a'] that would equal to 'b' string.

Length 5

<?=5?>

This is an example to write number 5 to output, this statement equal to <?php echo 5; ?>, don't forget to enable short_open_tag in your php.ini to enable this feature.

Length 4

NULL

NULL is a constant that holds the value of any variable that hasn't been set yet, or have been unset, or any variable/constant that has been assigned as NULL.

Length 3

1.2

This is example on how to create a float type value. Do not compare float values with equality == operator since they are imprecise. To check whether a variable is a float type, use is_float function.

Length 2

''

This is how you create an empty string in PHP, there are other way such as double quote "". For performance reason, always use single quote unless there are interpolation.

Length 1

a

Anything that written outside <? or <?php and ?> are treated as output, so, if a .php file containing only a character a, that character itself would be the output.

Factoid

Some of the biggest online sites, such as Facebook, Wikipedia, and Yahoo! are powered by PHP.

Kokizzu

Posted 2015-01-19T12:36:59.320

Reputation: 1 531

17 byte snippet: array() or $s?1:0;. – Ismael Miguel – 2015-01-23T15:22:29.290

28 byte snippet: <?=text; (it shows that you don't need the closing tag (useful for included files that aren't meant to produce output) and it shows that undefined constants are converted to strings (but raise a warning when doing so)). – Ismael Miguel – 2015-01-23T15:27:58.977

1

When you get a lot more of upvotes, you can use this one: <script language="php"> which is a valid opening tag. (Doc: http://php.net/manual/en/language.basic-syntax.phpmode.php)

– Ismael Miguel – 2015-01-23T15:35:23.737

the last one is new for me :3 thanks! – Kokizzu – 2015-01-23T16:35:53.117

1I got surprised when I found it, almost 1 year and a half ago. And you should specify that the constant __DIR__ is only available in PHP 5.3 and up. Also, a better way to implement includes is to use include dirname(__FILE__).'/file.php'; or include __DIR__.'/file.php'; which increase the performance by reducing a few filesystem lookups for relative paths. – Ismael Miguel – 2015-01-23T16:42:41.430

1

Also, a 0 byte snippet is an empty file being accessed with ?=PHPE9568F34-D428-11d2-A769-00AA001ACF42 at the end (e.g.: http://localhost/index.php?=PHPE9568F34-D428-11d2-A769-00AA001ACF42). It should display PHP's logo.

– Ismael Miguel – 2015-01-24T02:35:01.177

1I believe the comment on 4**3**2 is incorrect. It says the result 262144 comes from 64**2, which it does not. It comes from 4**9, as the **-operator is right associative. – Padarom – 2015-01-26T06:56:12.413

you're right.. edited – Kokizzu – 2015-01-26T07:05:46.797

@IsmaelMiguel if I understand right, when you need a special way to call a piece of code, that is included in the count for code-golf. So that would be a 39-byte snippet. – Paŭlo Ebermann – 2015-09-06T11:14:07.750

another one for 12 or 13 bytes: phpcredits(); creates a HTML page with info on PHP developers, authors of modules, etc. – Titus – 2016-09-20T14:39:09.290

28

OpenSCAD

OpenSCAD is a language used to create parametric and accurate 3d models using nothing but code. Note: I refer to CSG multiple times in this post; this stands for Constructive Solid Geometry. This means constructing a model through a combination of combining objects, subtracting objects, and intersecting objects.

Factoid:

Since a .scad file is plain text, it occupies very little space, and you can use tools like diff effectively.

Length 1:

Well, there isn't too much you can do with one character, but one very useful character is the debug modifier:

#

This character can be placed in front of any CSG tree to highlight it, even if it would be invisible in the final output (such as if the CSG object was subtracted from another object). I'm not allowed to write any more code to explain this, so I'll use pictures.

Without the modifier:

No modifier

With the modifier:

With modifier

(Image Source: OpenSCAD User Manual, Wikibooks, CC-BY-SA)

Length 2:

In OpenSCAD, you can create simple animations. How, you ask? This is done using a special variable for animation:

$t

This variable repeatedly loops from 0 to 1, which your code can use to change the position of an object, rotate an object, or do pretty much anything when combined with control flow structures. OpenSCAD can dump png frames at user specified intervals to create videos and/or gifs.

Adding a single line of code to a program (in this case, one of the examples, which also happens to be the OpenSCAD logo), and running the output through a gif maker can turn it into an animation like this: Rotating OpenSCAD logo

Length 3:

There are a wealth of libraries in OpenSCAD, and one way to access them is via the command:

use

There are actually two commands with similar functionality, but the other one has too many bytes. The main difference is that any top-level code (code outside a function/module) isn't executed with use, while it is executed for the other command. Both commands must be placed before any use of imported functions.

There are a couple of widely used libraries (Note that some of these should be added to the project with the other command instead):

  • MCAD- this contains basic utilities (more shapes, gears, some math, etc), and often is installed automatically with OpenSCAD.
  • Write.scad- Many of it's functions have been superseded by built-in functions in OpenSCAD, but it allows you to do a little more than the built-in functions can do (write curved text, for example).
  • BOLTS- This extensive library allows you to use standard hardware parts (and some non-standard hardware) in your projects.
  • The General Library of Relativity- Allows creating and positioning of objects relative to other objects.
  • String Theory- Made by the same person as Relativity, this provides various string utilities, along with regex functionality.

Length 4:

4 bytes is in that weird range where you can't really show off special variables or 1-character modifiers, but it's too short to really demonstrate the usage of a keyword.

However, it is the smallest whole program that isn't empty (or made up of only whitespace and semicolons) that compiles/runs without an error:

a=1;

This just assigns 1 to the constant a. In OpenSCAD, almost everything is a constant within its scope. Recursion, iteration, and defining separate constants are two common ways to circumvent this limitation. Note that OpenSCAD is dynamically typed.

Length 5:

Much of OpenSCAD's power comes from its conditional branching. Assuming that a is a boolean value, you can write:

if(a)

Alternatively, you can put in any expression that evaluates to a boolean. This may be followed by a single statement, or by a code block surrounded by braces. The if statement shouldn't be used to conditionally assign variables, however—Any variable re-assignment creates a scope for the new variable which effectively shadows, not replaces the original variable. Conditional variable assignment must be done on declaration of the variable, with the ternary operator.

Length 6:

This one is really cool:

hull()

It's the digital equivalent of wrapping a piece of plastic wrap around an object:

Without hull:

No hull

With hull:

Yes hull

Length 7:

This one isn't too exciting, but it is very useful:

[0:2:6]

This evaluates to an array. The first number is the starting value, the last number is the ending value, and the (optional) middle number is the step. For example, the previous line of code would evaluate to [0,2,4,6]. Arrays can be nested (jagged arrays and different levels of nesting are allowed) and they can be assigned to a variable.

Length 8:

This is one of the three main CSG operations in OpenSCAD:

union(){

Now would be a good time to talk about the tree structures in OpenSCAD. In OpenSCAD, every object (in terms of 3D modeling, not OOP; OpenSCAD is definitely not OOP) is a node on a tree, and each can contain sub-trees.

Every OpenSCAD model is built from a handful of built-in primitive objects (these primarily act as end-nodes), and various built-in operations (these typically contain their own sub-trees). Additionally, you can define your own operations that either transform their sub-trees, or create a model on its own—but that's a topic for later on.

Back to union: this operator wraps everything in its sub-tree into one node (but doesn't do anything to the objects themselves), so that they can be treated as one whole unit when used in other operations. It may not do much on its own, but when combined with other operations, it can be a vital tool.

Length 9:

Here's a mouthful:

minkowski

The minkowski function involves taking the minkowski sum of an object. This one is a bit weird, as it is taking one shape, and moving it around the surface of another object. It's hard to explain in words, so an image is definitely helpful.

Non-summed:

Not summed

Summed:

Summed

The same process can also be extrapolated into the third dimension:

3D Non Summed 3D Summed

Note that when using this, it can take a while for it to render, especially for more complex objects.

Length 10:

Here is another important CSG operation:

difference

This takes the first element of its sub-tree, and "subtracts" every other object in the sub-tree from it.

For example, in this picture, the cylinder is being subtracted from the cube. Note that the debug modifier is used to make the cylinder visible:

Difference

Length 11:

Finally, there are enough bytes to be able to define a module:

module a(){

A module in OpenSCAD can define an object, operate on objects, or both. Everything (including the built-ins) that creates or modifies objects (not numbers, booleans, arrays, or strings, though; those are for functions, which I'll talk about in another section) is a module. The module can also accept variables (and define default values), though you have to be careful, as OpenSCAD is dynamically typed. Some modules can operate on their sub-trees; however, most modules won't do anything if they are passed a sub-tree. More info can be found here.

Length 12:

Finally, the third major CSG operation

intersection

This takes the intersection of two objects.

For example, the intersection of these two objects:

Not Intersected

would be:

Intersected

Note that intersection doesn't work as expected when working with for loops, but there is a way around that. This may to change in future versions, however.

Length 13:

Everything so far has been a yellow (or translucent red) color. How boring! You can spice it up with colors like "mediumspringgreen" and such, but since that would put this over the length limit, I'll choose a different color:

color("cyan")

As expected, this changes the color of its subtree:

It's also "aqua"

The color module accepts any of the standard CSS/SVG color names, and can also accept a vector of RGB colors (scaled from 0-1, not 0-255) with an optional transparency. More info on color here.

Length 14:

OpenSCAD includes the for loop, for simple iteration:

for(i=[0:2:8])

There are a couple finer points when dealing with for loops. For one, the loop variable can iterate over any array. As stated in the Length 7 snippet, [0:2:8] simply evaluates to [0,2,4,6,8] when looped through. Since OpenSCAD isn't type safe, make sure that the loop body can handle the loop effectively. Besides a special for loop for dealing with intersections, there are a couple variations that greatly expand the for loop's capability that I'll describe when there are more bytes.

Length 15:

Adding to the list of built-in modules:

scale([x,y,z]){

(Note that [x,y,z] is a vector, which is basically an array in OpenSCAD. You can substitute the whole expression for a variable that equals a vector.) When applied to a sphere, you can do things like stretch it so it becomes a blimp-like shape:

Blimp

This command can be applied to any sub-tree and have a similar effect.

Length 16:

resize([5,8,10])

This command takes the bounding box of the subtree, and stretches (or shrinks) each axis to fit in a new bounding box. For example, say you have a sphere of radius 10:

Sphere

If you resize it to a 5x8x10 bounding box, it becomes:

Whatever this is

Length 17:

linear_extrude(h)

(where h means height)

If I take this 2D square (size 10x10):

Square

and I apply a linear extrude with a height of 5 to the square, then I get a rectangular prism:

Rectangular prism

Length 18:

While you can't set arrays from inside a for loop (the variable inside the for loop shadows the variable in the wider scope), OpenSCAD compensates by adding list comprehensions.

[for(i=[1:10])i*2]

This list comprehension iterates i from 1 through 10, and for each value of i, the result is 2i. This expression results in the array [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]. Note that this array could have been produced with [2:2:20].

Length 19:

import("model.stl");

(Note that STL is a file format for 3D models. It contains a triangular mesh of all of the surfaces in a model.)

If I save the hilbert cube model from here as model.stl in the same folder as the .scad file, OpenSCAD allows you to use it as a component of the model (e.g. you can perform CSG operations on the model).

Hilbert cube

Length 20:

Let's do some animation!

$vpr= [45,0,$t*360];

$vpr is a special variable in OpenSCAD. It contains the rotation of the viewport ($vpt and $vpd contain the translation and distance, respectively). If you assign them a new value, the viewport changes to that value.

As stated earlier, $t contains a value between 0 and 1.

To start with animation, click View > Animate. That will bring up a bar like this:

Bar

Time will automatically change when you configure the other two values. This becomes the value of $t.

Steps means the amount of steps that $t will go through between 0 and 1.

FPS is the amount of steps OpenSCAD will go through every second.

If "Dump Pictures" is selected, as OpenSCAD goes through the animation, it will save the pictures sequentially.

With the above code, 30 steps, and 10 FPS, I get this exciting animation:

Super exciting

Of course, you can use $t in other places as necessary.

Daniel M.

Posted 2015-01-19T12:36:59.320

Reputation: 3 737

1Looks like a very interesting language; I'd love to see more. :) – ETHproductions – 2015-10-08T18:35:49.023

I did not expect to see an OpenSCAD answer here, props! – cole – 2015-10-10T03:59:52.150

28

LOLCODE

Note: I will be following previous rules of this showcase before mods stepped in, in that the length of my longest snippet will be equal to the number of votes this post has.


25 characters

HAI 1.3
VISIBLE 1
KTHXBYE

This is a complete program that prints 1 to the standard output.

24 characters

HOW IS I z
3
IF U SAY SO

Defines a function z that when called, returns 3.

23 characters

VISIBLE SUM OF a AN 32

Prints variable a plus 32.

22 characters

I HAS A var
GIMMEH var

Create a variable and assign input to it.

21 characters

VISIBLE “HAI WURLDZ!”

The LOLCODE Hello World Program!!! w00t w00t!

20 characters

I HAS A big ITZ FAIL

Creates a variable big and assigns it to FAIL, the falsy boolean.

19 characters

QUOSHUNT OF 99 AN 9

Returns 11, 99 divided by 9.

18 characters

I HAS A var ITZ 99

Creates variable var and assigns it the value 99, a NUMBR.

17 characters

O RLY?
YA RLY
OIC

Similar to the last snippet, this is a blank if statement. O RLY? takes the value in IT and tests it for truthiness. If true, it runs the code in the YA RLY block, then exits at OIC.

16 characters

WTF?
OMGWTF
OIC

A switch/case statement. Takes the variable in IT (the runtime temporary variable) and matches it up with any OMG <value> statements. Since there are none, it goes right to OMGWTF, the default statement. Since there is no code in the block, it goes right to OIC and continues with the code.

15 characters

HAI 1.3
KTHXBYE

The shortest complete program. All LOLCODE programs start with a version number and end with KTHXBYE.

14 characters

DIFF OF 9 AN 6

Returns the difference of 9 and 6

13 characters

CAN HAS TIME?

Imports the library TIME if it exists.

12 characters

GIMMEH INPTZ

Gets input from STDIN and saves it to the already-defined variable INPTZ.

11 characters

OBTW
C
TLDR

A multi-line comment (C is the content)

10 charaters

VISIBLE 10

Prints 10 to STDOUT.

9 characters

I HAS A Z

Creates a variable called Z.

8 characters

VISIBLE 

(note the trailing space) Prints… nothing.

7 characters

HAI 1.3

The hello() of LOLCODE.

6 characters

GIMMEH

A function asking for input from STDIN. This does nothing as it's not assigned to a variable though.

5 characters

Y R 6

Assigns the NUMBR 6 to the already-defined variable Y

4 characters

":)"

A newline inside a YARN. THE : character is the escape character inside strings.

3 characters

BTW

An empty comment. w00t.

2 characters

""

An empty YARN

1 character

I cantz do real stuff with my 1 char!!

-- Hohmannfan

3

It da NUMBR 3.

Factoid

Is composed almost completely with Internet slang.

OldBunny2800

Posted 2015-01-19T12:36:59.320

Reputation: 1 379

41 character: "I cantz do real stuff with my 1 char!!" – SE - stop firing the good guys – 2016-04-14T22:27:24.177

1yah me cantz ur rite – OldBunny2800 – 2016-04-14T22:55:00.390

1CAN I HAZ LENGTH 10? sorry for shouting :3 – fede s. – 2016-04-25T02:15:53.983

1YA U CAN HAZ LENF 10 – OldBunny2800 – 2016-04-25T21:18:34.280

1I HAZ A VAR; VAR R 12; CAN HAZ LENF R?!!??!?!; GIMMEH! – cat – 2016-04-28T02:34:01.957

1Output: TROOF – OldBunny2800 – 2016-04-28T02:34:35.790

26

Agda

Factoid:

Agda is a Haskell inspired language with even more advanced type system, that makes it possible to declare statements about programs and proof their validity. It comes with proof assistant tools, embedded into Emacs, so you can use it interactively to construct mathematical proofs.

1

_

Underscore has bunch of meanings in Agda. It can mean a wildcard, meaning you don't care about naming stuff when you pattern match. It can tell Agda to guess values or types, which it does by solving type equations. Or as a placeholder in function definitions, it can be placed nearly anywhere, so that definition of post,pre,infix operators are possible (e.g. _! can define factorial and if_then_else_ a condition clause).

2

()

An absurd pattern. Doing a pattern match on an absurd pattern tells Agda, that this pattern is impossible. Or in other words, we trying to match to an empty type (bottom ), the type with no values.

3

Set

Types and values in Agda are treated similarly. As value can be of a certain type, the type itself can be of a type of something, this something is called Set. For example 0 : ℕ : Set means that zero has type of natural numbers (or just 0 is a natural number) and natural numbers are of type Set (or natural numbers represent type or set). But it doesn't end here, because even Set has type Set₁, which has type Set₂ and all the way up to infinity (and beyond).

4

data keyword is used to define types in Haskell's GADT (Generalized Algebraic Data Types) style. Here are some examples

Empty type

data ⊥ : Set where

Boolean type

data Bool : Set where
  false : Bool
  true : Bool

Natural numbers

data ℕ : Set where
  zero : ℕ
  suc : ℕ → ℕ

5

f = f

Spaces around operators are mandatory, so we can only now construct some simple definition. This snippet is a valid definition of non-interrupting program in Haskell, but it won't compile in Agda due to the Termination check failure. Agda is a total language, meaning every program in it should terminate and there is no way to construct a valid non-terminating function. The reason behind it is that this function can be of an arbitrary type f : ∀ A → A, and due to Curry–Howard isomorphism between programs and proofs, constructing a value of any type basically means that we proved everything!

6

record

Agda has records, datatypes with single constructor. For example we can define a pair like so

record Π (A B : Set) : Set where
  constructor _,_
  field
    first  : A
    second : B

And we can define pairs now p = (zero , false) (parenthesis can be omitted) and extract fields from them: Π.first p is zero and Π.second p is false.

Also there is a convention to define a type with one element as an empty record

record ⊤ : Set where

There is only one value of type , which automatically deduced to be an empty record record {}, it can be used to define true propositions.

7

∃ n = n

For an arbitrary type of n this is just an identity function, but if it has type for example ∃ : ℕ → ℕ then it can be interpreted as a proof that natural numbers exist!

8

λ n -> n

The same identity function can be written as an anonymous function (lambda). It can be written as a 7 length snippet with instead of ->, but I can't come up with a more interesting 8-snippet otherwise.

9

λ x _ → x

This would be a definition of a constant function that returns its first argument and discards the second. A complete defintion with the most general type that works with argument types of any universe looks like this

const : ∀ {α β}
       → {A : Set α} {B : Set β}
       → (A → B → A)
const = λ x _ → x

Stuff inside curly brackets {} tells Agda that this variables are implicit and they should be decided based on the explicit variables A and B. It's possible to include them anyways like this const {α} {β} {A} {B} x _ = x.

10

Th = ⊥ → ⊤

Here I defined a theorem Th : false implies true. I can prove it by constructing a value of type Th. As I mentioned earlier a true proposition has only one value and it also represents an empty record and the proof would be just returning it

f→t : Th
f→t = λ _ → record {}

Similarly we can proof ⊤ → ⊤ or ∀ A → ⊤, so basically anything implies true propositions. Contrary to false propositions, which can't be proven without constructing a value of empty type. We can proof ⊥ → ⊥ by absurd pattern and ⊤ → ⊥ can't be proven. Therefore a complete implication table in Agda is represented in following statements

f→t : ⊥ → ⊤
f→t = λ _ → record {} -- empty record

t→t : ⊤ → ⊤
t→t = f→t -- same proof

f→f : ⊥ → ⊥
f→f () -- absurd pattern

t→f : ⊤ → ⊥
t→f = {!!} -- nothing could be written here, just a hole

11

¬ P = P → ⊥

The definition of propositional negation. You can look at it this way: if ¬ P is true then P is false and therefore should imply false (P also should be implied from false, but everything is implied from ). Given this definition it is possible to prove some theorems, like contradiction A → ¬ A → B, contraposition (A → B) → (¬ B → ¬ A), double negation A → ¬ (¬ A) and ¬ (¬ (¬ A)) → ¬ A. Note that Agda being an intuitionistic system, the double negation elimination ¬ (¬ A) → A is not a theorem: "It's not the case that it's not raining" doesn't mean "it's raining", but only that the rain would not be contradictory.

12

Usually in is written as , but I'm short of one character

x in P = P x

Types of functions from type A to some Set _ can be thought of as a usual set in maths sense, set membership therefore has type _∈_ : ∀ {ℓ} → A → (A → Set ℓ) → Set _. Empty set is then simply ∅ = λ _ → ⊥ and the universe (the set that contains every element of type A) is U = λ _ → ⊤. Other related definitions include

x ∉ P = ¬ x ∈ P
∁ P = λ x → x ∉ P -- complement set of P
P ⊆ Q = ∀ {x} → x ∈ P → x ∈ Q -- subset

13

V A : ℕ → Set

This is a simplest data declaration for vectors (lists with size). The full definition with constructors looks something like this

data V A : ℕ → Set where
    []  : V A zero
    _∷_ : ∀ {n} → A → V A n → V A (succ n)

Notice that it's a dependent type, it depends on the value of type ! Now the function like head which returns the first element of a vector can be defined without worrying about empty vector case, we just give it a type that works only with non-empty vectors like so

head : ∀ {n} → V A (succ n) → A
head (a ∷ as) = a

swish

Posted 2015-01-19T12:36:59.320

Reputation: 7 484

Wow! Where do I get a compiler / interpreter? – cat – 2016-04-28T02:38:23.560

@cat sure

– swish – 2016-05-08T00:05:32.597

26

Ruby

Created by Yukihiro "Matz" Matsumoto in 1995, Ruby is a dynamical object-oriented programming language. It's built/inspired by Perl, Smalltalk, Eiffel, Ada, and Lisp.

Matz, speaking on the Ruby-Talk mailing list, May 12th, 2000.

Ruby is simple in appearance, but is very complex inside, just like our human body

Factoid
In Ruby everything is objects, so no primitives. Parentheses are also optional. Opening up for some interesting coding, but that doesn't mean that you have to avoid them.
Is this really that readable?

puts array.delete hash.fetch :foo

Snippet 1
Use the $ to create global variables, but don't clutter the namespace please.

Snippet 2
To create a new hash, all you need to type is {}.

Snippet 3
Ruby uses nil as a false value. So no need to do var.nil? everywhere.

Snippet 4
puts is used to print a string version of an object with a new line at the end. Short for "put string". Can also be shortened to just p.

Snippet 5
To make Ruby even more powerful it handles closures. And with the use of f.call you can call/invoke a block or function. Pretty sweet. For those unfamiliar with closures. A closure can pass it around like an object (to be called later). It also remembers the values of all the variables that were in scope when the function was created. It can access those variables when it is called even though they may no longer be in scope.

Snippet 6
The snippet class C returns nil, and that is because everything in Ruby has a return value. You can even return multiple values.

Snippet 7
With the use of include Ruby support single inheritance. Making it easy to mixin modules.

Snippet 8
x||=true is one of several logical operators that Ruby supports. This one checks if x has been defined, and if not sets it to true.

Snippet 9
Fo.new(x) calls the class Fo initialize function, with the value of x. There is no constructor in Ruby so you are free to return what value you like from the .new() call.

Snippet 10
As mentioned earlier Ruby supports multiple return values, and it is easily done with return x,y. The values are returned as they are read, and if you have more return values then what you have for assigning the rest will be dropped. Using the * on the last variable will make an array and assign the rest of the return values to that array.

Snippet 11
RubyGems is the packet manager for Ruby started in November, 2003. Original a stand alone program, but as of Ruby 1.9 it is a part of the standard library. Use the code snippet gem install and the name of the package (for example 'sinatra') to install it.

Snippet 12
[1,2]<<[3,4] The command '<<' pushes or append a object to the array. In our case the array [3,4] will be pushed 'into' the array [1,2], making it 'look' like this [1,2,[3,4]]. So it does not merge two arrays.

Snippet 13
x.map{|y|y+1} The map function iterates over the array 'x' and invokes the block given, and returning a new array with the modified values. In our case it will iterate over the values in the array and increment them with one.

Snippet 14
x.map!{|y|y+1} This snippet is similar to the previous one, but calls on the function map!. The '!'/exclamation mark tells the user that this function will modify the object calling it, often called destructive or dangerous functions.

Snippet 15
The snippet ARGV[0] ||false checks if ARGV[0] evaluates to true, if not it will return the or value, false. ARGV is an array containing the arguments sent in at start time. ruby app.rb test will give you 'test' in ARGV[0].

PS: Also check out this post about Ruby

Kyrremann

Posted 2015-01-19T12:36:59.320

Reputation: 361

1 more upvote. p should be there I think – Anwar – 2016-10-24T08:51:24.857

26

JavaScript, EcmaScript 6

I will be focusing on features/snippets of/from ES6 standard in this answer. Some snippets require knowledge of topics previously presented, so you may want to read this bottom-to-top.

Length 17 snippet:

"".codePointAt()

More Unicode support! .codePointAt() is a Unicode-compliant version of .charCodeAt(). For example, if you were to take

"".charCodeAt()

you would find 55362. This might seem right, but if you convert it to hexadecimal, you would find that it corresponds to U+D842. Looking on Graphemica, we can see that the character is actually U+20BB7. U+D842 is one of the two surrogates that makes up the UTF-16 representation of that character.

But enough of these details: the point of .codePointAt() is to find the actual Unicode point of the character. "".codePointAt() is 134071, or U+20BB7—the correct result. Finally Unicode lovers can use JavaScript!

Length 16 snippet:

/^.$/u.test("")

Another nice feature of ES6 is proper Unicode support! If you tried this code in ES5:

alert(/^.$/.test(""))

You might be surprised to find that the answer is false! The problem here is in JavaScript's default encoding, UTF-16: characters above U+FFFF are actually represented as 2 chars, called "surrogates". (You can learn more about this on Wikipedia.) In order to fix this, you need a more complex regex:

alert(/^(?:[\uD800-\uDBFF][\uDC00-\uDFFF]|.)$/.test(""))

ES6 introduces the u flag on regexes. When u is set, characters above U+FFFF are still captured as a single char. So /^.$/u.test("") returns the correct result: true.

Length 15 snippet:

String.raw`q\n`

Back to tagged templates! ES6 comes with a function all set up to be used as a tag: String.raw. This returns the raw text you typed in the template (replacing interpolations with their values), so the above snippet is equalivalent to "q\\n".

Length 14 snippet:

Number.EPSILON

As you may know, JavaScript's numbers are not arbitrary-precision; they have exactly 53 bits of precision. This can cause problems when trying to add decimal numbers:

var point3 = 0.1 + 0.2;
alert(point3 === 0.3); // false!

The problem here is that neither 0.1 nor 0.2 can be represented exactly in binary, and when adding them together, the least significant bit is rounded the wrong way, resulting in 0.30000000000000004 instead of 0.3.

Number.EPSILON was added as a workaround to this problem; it is equal to 2-53, the smallest number that can be added to 1 without rounding back down to 1. We can use this to create a new equals function:

equals = (num1, num2) => Math.abs(num1 - num2) < Number.EPSILON;

alert(equals(point3, 0.3)); // true!

Hooray for ES6!

Length 13 snippet:

s=>s.split` `

What is this? A function call without parentheses? Actually, it's another use of template literals: tagged templates! But what is actually happening here?

When you tag a template with a function, it calls the function as usual, but it passes in the arguments a little differently. Take this example function:

function parseMe(strings, name, age) {
  alert(`Your name is ${ name } and you are ${ age } years old`);
  console.log("We don't need these strings:", strings);
}

myName = "Bob";
myAge = 123;
parseMe `Hello, I'm ${ myName } and I've orbited the earth ${ myAge } times.`;

This alerts Your name is Bob and you are 123 years old. Why? When calling a function with a tagged template, JavaScript passes each ${ } value as a separate parameter, groups the strings into an array which is passed before everything else. So you're really calling parseMe like this:

parseMe( ["Hello, I'm ", " and I've orbited the earth ", "times."], myName, myAge );

Cool, right? Now back to the original snippet. Now we can see that it could be written like this:

s=>s.split([" "])

.split coerces its argument to a string before splitting. The string representation of [" "] is " ", so the function could be written yet another way:

s=>s.split(" ")

And this simply splits the text on spaces, which splits it into words. Isn't ES6 awesome?

Length 12 snippet:

n=>`Hi
${n}`

Introducing...template literals! Yet another super-helpful ES6 feature. These act like strings for the most part, but you can include newlines without escaping them. Not only that, but you can also use interpolation! If you run the above function with input "JavaScript", it will output this:

Hi
JavaScript

Length 11 snippet:

[a,b]=[b,a]

Tired of using that old var tmp = a; a = b; b = tmp; trick to swap variables? Now you don't have to! Using destructuring, you can swap those two variables quickly and concisely with the above statement.

Length 10 snippet:

[a,...b]=b

Destructuring! Yay! This is one of the cooler features of ES6. You can use it to do many things that would have taken a lot more bytes in ES5. For example, this is what the above statement corresponds to in ES5:

a=b[0],b=b.slice(1)

Actually, a=b.unshift() works too, but consider when you want to grab the first three items:

[x,y,z,...b]=b
x=b.unshift(),y=b.unshift(),z=b.unshift()

Or if you don't want to change the value of b:

[x,y,z]=b
x=b[0],y=b[1],z=b[2]

As you can see, destructuring is shorter, more readable, and just all-around better.

Length 9 snippet:

new Set()

Another useful data-type that JavaScript now supports is Sets! You can create a set like so:

var myArray = [1, 3, 6, 3, 2, 1];
var mySet = new Set(myArray);
// Set [ 1, 3, 6, 2 ]

As you can see, creating a Set out of an array removes all duplicate items. You can turn it back into an array with the spread operator:

myArray = [...mySet];
// [ 1, 3, 6, 2 ]

You can also use this trick on strings:

var myString = "Hello, World!";
var mySet = new Set(myString);
myString = [...mySet].join("");
// "Helo, Wrd!"

Keep in mind that the Set constructor must be called with new, and only works on the first argument. For example, this won't work:

var mySet = new Set(1, 3, 6, 3, 2, 1);
// TypeError: 1 is not iterable

You can learn all about Sets on this page.

Length 8 snippet:

(i=0)=>i

You probably understand what this example is: default parameters! JavaScript ES5 is really horrible with default values. Usually you can get away with this workaround:

function f(i) {
  i = i || 0;
  return i;
}

However, this resets i if it is anything falsy (false, 0, "", null, or undefined). To just do null or undefined, you have to be much more verbose:

function f(i) {
  if (typeof i === "undefined" || i === null)
    i = 0;
  return i;
}

But ES6 contains a new syntax for default values! Now you can shorten your code to this:

function f(i = 0) {
  return i;
}

Or in ES6 arrow notation, f=(i=0)=>i. When given an input, this just returns the input, but when called with no input, it returns 0. This is very helpful in uncountable scenarios, and possibly one of the best additions of ES6.

Length 6 snippet:

Symbol

JavaScript now supports Symbols! A symbol is created with Symbol("foo"), and every symbol created is different: Symbol("foo") !== Symbol("foo") The only way to keep a symbol is to assign it to a variable: var sym = Symbol("foo"); sym === sym

One of the most useful Symbols is Symbol.iterator. This is a Generator which is used whenever you iterate over an object, whether with for-in loops or the ... operator (see below). For example, the following code defines an iterator for all Number objects:

Number.prototype[Symbol.iterator] = function* () {
    for(var i = 0; i < this; i++)
        yield i;
}

Now [...6] returns [0,1,2,3,4,5]! Aren't generators fun?

Length 5 snippet:

const

This for a change is exactly what you've guessed! Its a new variable declaration syntax used for creating constant variables.

const a = "foo";

Now a's value is fixed, any attempt to change it will lead to a SyntaxError (cos JS!). Not only that, if you skip the assignment part while declaring the variable, that will also lead to a SyntaxError.

const a;
// Exception: SyntaxError: missing = in const declaration

const a = "foo";
a = "bar";
// Exception: SyntaxError: invalid assignment to const a

Length 3 snippet:

...

Default arguments ? Java ? Nope! This is the new spread operator and it does exactly what it says.

For instance, you want to spread your array variable A into another array B in the middle alongside other things:

var B = [1, 2, 5, ...A, 8, 0];

That simple!

You can even do this with function calls or arguments.

function foo(a, b, ...c) {}

is a function whose first argument goes in a, second goes in b and rest all arguments (third, fourth ...) go in as an array in c.

Now if you want to call that function and all your arguments are in the array A, you can do it like

foo(...A);

Length 2 snippet:

=>

Think that I put greater than or equal to sign the wrong way ? Think again! Think ES6!

This is one of the best features of ES6 - Fat arrow function . Apart from reducing a lot of bytes while defining a function (var a=_=>_+_ instead of var a = function(_){return _+_}), arrow functions also change the behavior of this so that you don't have to bind the function again and again.

Length 1 snippet:

*

Multiplication ? Nope! Remember ES6! The * keywords is part of one of many syntax sugar + features of ES6 - Generators. This is added to the function keyword to make the function a generator function.

Factoid

ES6 adds a lot of useful syntax sugar and features into the language inspired by a lot of other languages.

The most useful fact about ES6 is that due to the added syntax and features, it performs much better than ES5 (current generation JS across all browsers) in terms of .

The final spec for ES6 was finalized in June 2015, and all major browsers (except IE) have enabled most of the new features. You can check this page to see which features your browser supports, as well as all major browsers and other environments.

Optimizer

Posted 2015-01-19T12:36:59.320

Reputation: 25 836

2I can't wait till ES6 is usable in production – DanielST – 2015-02-05T21:11:22.073

Nice showcase of the new features! Could you add a few more, please? :-) – ETHproductions – 2015-09-30T04:09:16.250

Sure, I'll try to update today or tomorrow. – Optimizer – 2015-09-30T04:14:16.653

1^‌‌‌‌‌‌‌‌‌‌‌ ;) – ETHproductions – 2015-11-29T04:21:37.680

2Well, this answer now has 18 upvotes, could you update it? – Michał Perłakowski – 2016-04-11T18:50:48.323

May I please add a few snippets? – ETHproductions – 2016-10-22T19:49:41.643

@ETHproductions please feel free to! thanks in advance! – Optimizer – 2016-10-22T20:15:44.273

+1 for =_=, lol. – Oliver Ni – 2016-10-24T02:55:47.660

@Gothdo It now has 23 upvotes, and I'm in the process of updating it :) – ETHproductions – 2016-10-25T17:54:48.143

26

μ-recursive functions

These come in many flavors, but are all essentially the same: a "functional assembly" of sorts.

Factoid: μ-recursive functions are a Turing-complete model of computation that, unlike Lambda calculus (which is theoretically equivalent to it) has no more-or-less popular language based on it. Why? Because it manages to combine the readability of (((((Lisp)))))) with the eloquence of assembly. However, there are interpreters for several langauges that are actually flavors of μ. None of them, however, can operate with anything but unsigned integers. Pity.

μ, by default, supports only 2 datatypes - an unsigned integer and a function. Operators recieve and return functions, functions recieve and return unsigned integers. Simple and straightforward. That's all there is to the entire language.

If this recieves enough upvotes, I'll be providing snippets in RF, a small language based on μ-recursive functions created for educational purposes by a teacher at a university where some friends of mine study. It uses a flavor of μ that is a bit different from Kleene's. You can download it here: http://www.mediafire.com/download/fnsyze4crthgl89/rf_setup.rar (warning: entire interface is in Russian; function definitions go into the top text field, function calls go into the bottom left one, results get output to the bottom right one).

Length 1 snippet:

N

This is not runnable code, sadly. I'd need at least 5 upvotes for the first runnable RF snippet.

This is one of the 3 built-in functions supported by μ, the successor function. What does it do? Well, it simply takes one number as an input and returns this number + 1. It's also sometimes abbreviated as s in different μ languages.

Length 3 snippet:

f()

This is the shortest possible "input" call of a μ-recursive function. It calls a 0-ary (parameterless) function f with, well, no parameters.

As μ is a 100% pure functional language, input is restricted to function calls, and output is restricted to function return values. All μ-based languages, including RF, provide a way to list the function calls that the program should recieve as "input". Note that this specific example won't run in RF because it requires function calls to have a ; at the end, but it could run in another μ-based language.

Length 4 snippet:

M(O)

This is one of μ's 3 operators: the minimisation operator, sometimes abbreviated as μ. Obviously, it gives the model of computation its name. This specific snippet synthesizes and returns a 0-ary function that always returns 0.

Now, this calls for a little bit of theory.

What does this operator do? Its workings can be written concisely as follows:

M(f(a1, a2, ... an-1, an)) called with arguments (a1, a2, ... an-1) returns the least value of an satisfying the condition f(a1, a2, ... an-1, an) == 0

It takes an n-ary function f as input, and synthesizes and returns an n-1-ary function (i.e. taking one argument less than the input function).

What does the returned function do? When called with some arguments (a1, a2, ... an-1), it forwards them to the input function f. It then finds the least possible (i.e. starting from 0) value of the last argument (an) which, together with the forwarded arguments, will make f return 0. If f doesn't ever return 0 in these conditions - hello, endless loop. If it does, the synthesized function returns the value of an it found.

In the snippet above, the operator takes the 1-ary built-in function O, and synthesizes a 1 - 1 = 0-ary function which finds and returns the least value of the last (and, in this case, the first) argument that would make O return 0. As O happens to always return 0, the least value of the argument would be 0. That is what the synthesized function will return.

Interesting note: there are two main different notation for this, as well as the other operators. Kleene, for example, uses a notation that is the inverse of the one RF uses: in his texts, an is actually the first argument of the input function f, not the last one. However, this doesn't really matter.

Length 5 snippet:

O(1);

I promised a runnable RF snippet, now, here you go. This is a RF function call "input". It calls the built-in 1-ary function O mentioned in the previous snippet, which always returns 0, no matter what you pass to it. It can be really, really useful at times.

Length 6 snippet:

I[1,2]

This is the identity function, one of the 3 built-in functions. It can take several arguments and return one of them. It is defined as I[i,n](a1, a2, ... an) = ai

You can think of it as a function "template" of sorts. The square brackets can take 2 constant (nonzero unsigned integer) parameters, which determine the identity function's behaviour. The second parameter in the brackets is the number of the function's actual parameters. The first one is the index, starting from one, of the parameter that the function returns. For example, the function shown above can be read as follows: "define a function which takes 2 parameters and returns the 1st one".

Length 7 snippet:

S(N,O);

We finally reached another operator! S is the superposition operator. The piece of code above uses it to create an 1-ary function that always returns 1.

This operator can be expressed as follows: S(f0, f1,f2, ... fn) called with arguments (a1, a2, ... am) = f0(f1(a1, a2, ... am), f2(a1, a2, ... am), ... fn(a1, a2, ... am))

At least 2 functions should be supplied to the operator. f0, the first function, should have an arity equal to the number of functions passed to the operator besides it (i.e. for f1,f2, ... fn, the arity of f0 should be n). It cannot be a 0-ary function. All other functions passed to the operator should have an equal arity (i.e. f1,f2, ... fn should all have the arity m). The synthesized function shall also have this arity (m).

The synthesized function first calls all but the first of the operator's argument functions with the arguments passed to it, and then calls the first of the operator's argument functions with the others' return values and returns its result.

In the snippet above, for example, when we pass an argument to the created function, it calls O with this argument, which returns 0. Then it calls N with this return value, which returns 0+1 = 1, so the synthesized function also returns 1.

Length 8 snippet:

zo=M(O);

This is a function definition! You can call it with zo();. It defines the zero-arity (parameterless) function returning 0 that I already discussed above.

Now we're getting to the fun part, recursion!

Length 15 snippet:

f=R(zo,I[2,2]);

Here zo is the previously defined (length 8 snippet) function.

R is the recursion operator. The above snippet defines a recursive function that takes one input parameter, decrements it until it reaches zero, then returns zero.

This operator can be expressed as follows: f = S(f0, f1) called with arguments (a1, a2, ...a{m-1}, am) = if am > 0: f1(a1, a2, ... a{m-1}, am - 1, f(a1, a2, ... a{m-1}, am - 1)); if am == 0: f0(a1, a2, ... a{m-1}).

This is basically good old tail recursion, plain and simple.

Let's see how the function above works for a parameter x: first, we have f(x). If x > 0, we return I[2,2](x - 1, f(x - 1)), which is the same as f(x - 1), and so on until we reach f(0), in which case we return zo(), i.e. 0.

The recursion operator is very important in μ-recursive functions, it's the backbone of most of the logic. However, some of its uses may seem a bit strange:

Length 16 snippet:

de=R(zo,I[1,2]);

This function takes one parameter x and returns x - 1 (decrements), if x > 0, and returns 0 if x == 0. Implementing it as a counterpart to N is instrumental in implementing subtraction (just as N is necessary in addition).

This use of the recursion operator may be considered strange because, well, there's actually no recursion going on here at all! Consider: if x > 0, de(x) = I[1,2](x-1, de(x-1)), equivalent to simply x-1, so the tail call de(x-1) doesn't even happen! And if x == 0, it simply returns zo(), or 0.

Length 18 snippet:

de3p=S(de,I[3,3]);

I see we didn't have an example for the superposition operator already, but here we go now. This defines a function de3p which, using the previously-defined de, takes 3 parameters and decrements the last one (calling it as de(I[3,3](x,y,z)) = de(z), where x, y and z are the 3 parameters).

Using this function, we can now define subtraction!

Length 19 snippet:

sub=R(I[1,1],de3p);

The sub function takes two parameters, x and y, and returns x - y. How it does that is quite obvious: if y > 0, sub(x,y) = de3p(x,y-1,sub(x,y-1)) = sub(x,y-1) - 1. And if y == 0, sub(x,y) = I[1,1](x) = x. So, basically, the function calls itself until y is 0, then takes x and backtracks for y steps, subtracting 1 from x on every step, resulting in x - y.

Length 20 snippet:

next3p=S(N,I[3,3]);

I decided to show a runnable example with every built-in function and operator; this is the last one, the built-in function N. This defines a function next3p, which takes 3 parameters and increments the last one by 1: next3p(x,y,z) = z + 1. This is pretty much by analogy with the previous example and doesn't really need an explanation.

Now, using this example, we can do addition!

Length 21 snippet:

ad=R(I[1,1],next3p);

This defines a function ad which takes 2 parameters and adds them together. It works the exact same way as the subtraction function, the only difference being that 1 is added to x on every backtracking step.

Mints97

Posted 2015-01-19T12:36:59.320

Reputation: 561

can you show how would it be possible to subtract one from an input, or check for equality? – proud haskeller – 2016-04-09T01:24:19.193

lots of upvotes! please update? – Conor O'Brien – 2016-05-03T04:21:55.563

1@proudhaskeller: I added examples for recursion, decrementing, subtracting and adding. Checking for equality is more verbose, but a simple way to check if x==y is to subtract x from y, then y from x, then sum the results: if the final result is 0, the two numbers are equal, if it's not, they're not equal (using the defs in the answer, it'll be something like eq=S(ad,S(sub,I[1,2],I[2,2]),S(sub,I[2,2],I[1,2]));). – Mints97 – 2016-05-11T15:03:33.057

@CᴏɴᴏʀO'Bʀɪᴇɴ: I updated the answer with some new examples. – Mints97 – 2016-05-11T15:04:12.730

Cool! Just checking if I understood correctly: b=R(O(O),S(N,S(O,I[1,2]))); is a function that returns 0 on 0 and 1 on everything else. – proud haskeller – 2016-05-11T15:35:36.827

2Fascinating. This is some beautiful stuff – Conor O'Brien – 2016-05-11T16:50:18.123

@proudhaskeller: if you mean M(O) instead of O(O), then yes, it should and does work (although not in the interpreter version linked above, as it doesn't allow nested M(f) operator calls because of a bug, you'd need to define zo=M(O); and use it instead). – Mints97 – 2016-05-11T19:26:02.427

@Mints97 but why shouldn't this work? O is a one ary function returning 0, so I apply it to something and get zero. Or is O's input should be of some specific type? – proud haskeller – 2016-05-11T19:36:51.957

@proudhaskeller: ok, now remember this: the first argument to R should have an arity that's one less than the desired synthesized function. Your desired function has an arity of 1, as the second argument has an arity of 2. This means that the first argument to R should have an arity of 0 to match the second one. And O(O) would have an arity of 1, and wouldn't work even if this syntax was legal - except that it isn't, and O(O) should be expressed as S(O,O). – Mints97 – 2016-05-11T20:22:05.797

26

Befunge-98

(No love for my favorite language?)

Befunge is a 2D programming language operating on a toroidal space - the 'grid'. In addition to the normal operators (all of which are single ASCII characters), there are also special instructions that change the direction in which the instruction pointer moves through the grid. The language was designed to be as hard as possible to compile, to this end, it contains elements of self-modification.

There are two versions of Befunge: Befunge-93, the first version (which limits the grid size to 80x25 and, as such, is not Turing-complete); and Befunge-98, the final specification (which allows unlimited grid size and much other useful functionality). In this post, I will use Befunge-98 for the code snippets because I feel it is the more useful of the two; a note will be included next to those snippets which are compatible with Befunge-93.

I recommend using CCBI to run longer code in Befunge-98. There are some other options for if you want to see Funge-space and the stack while the program is running: this online Befunge-93 interpreter (with 'klunky' input), and this online Befunge-98 interpreter (with no input at all, though it runs fast).

Snippets

Length 1 (Also works in Befunge-93)

.

Prints out 0, forever and ever and ever. Because Befunge's space is toroidal, the pointer wraps around when it encounters an edge. Befunge starts with an empty stack for its memory; trying to pop or do operations on an empty stack makes it 'generate' as many zeroes as needed for the operation.

Length 3 (Also works in Befunge-93)

&.@

(Still kind of a boring example, but less so.) This one accepts a decimal number (&) from stdin and prints it (.) to stdout. Then - aha, a new feature! - it terminates at the @. This is a pretty boring program, but you can only do so much with three characters...

Length 4 (Also works in Befunge-93)

1+:.

Another infinitely looping program. Each loop takes the top number on the stack and increments it, duplicates it (with :), and prints one of the duplicates, leaving the other on the stack for the next loop. (Since printing a number removes it from the stack, duplication is needed in order to keep a copy.) The result of this is a program that prints the positive integers, starting from 1.

Length 6 (Also works in Befunge-93)

8:*00p

Unless the user can watch Funge-space while the program is executing, this program appears to do nothing. In fact, it even terminates, rather than looping infinitely. "How?" you might ask. "You said before that the @ operator ends the program, and there is no such thing here!" Here lies one of the most intriguing aspects of Befunge: the ability for the program to modify its own instruction space.

The p operator takes a number, let's call it n, and a coordinate pair x, y (in order such that y is on top of the stack), and puts the character with codepoint n in the Funge-space grid square at the given coordinates. In this case, it puts an @ (ASCII value 64, or 8*8, or 8:*) at position 0, 0 - the top-left corner of the program, where the 8 is initially. Then, wrapping around, the pointer hits the @ it just set down and stops - the program has modified its own code. There is also a g operator that grabs the value of the character at the given coordinates; in this way, the program space can also be used as program memory that's more convenient than the stack.

Here's where Befunge starts to show its true colors! It's a cunning and devious language.

Length 7

~:a`j@,

Here we start seeing interesting constructions, and also some features that are not in Befunge-93. This program takes exactly one line of text and prints it out again - specifically, it keeps accepting characters from stdin (using ~) and checking whether the character is greater than 10 (a, new to -98), the value of a newline. If it is, it prints; if not, it terminates. This is accomplished using j (also new to -98), our first control operator - which pops a value and jumps over that many instructions - in this case either 1 (if the character value is greater than 10) or 0 (if it is not).

Length 8

1#;::.+;

This introduces the # operator, or trampoline, which jumps the instruction pointer over the next symbol to execute - the same as 1j. It originated in Befunge-93, due to the necessity of such an operator in a two-dimentional language. We can also see ;, a 98-exclusive operator that also moves the pointer around - this one jumps it all the way to the next ; along the direction the pointer is moving. Here it's used to create an infinite loop so the initial 1 only pushes a 1 at the beginning. The end result is a program that prints out, starting at 1, sequential powers of 2 forever and ever.

Kasran

Posted 2015-01-19T12:36:59.320

Reputation: 681

I feel your pain. I think this contest is over and my awk entry was just made too late. – kojiro – 2015-01-28T15:12:16.003

2

I feel your pain too and upvoted you, if you're feeling kind you might watch my Rebmu video in return :-)

– HostileFork says dont trust SE – 2015-01-28T16:46:15.517

@Kasran You have 21 up-votes now. You could publish some pretty interesting things. Some ideas: random number generator, maze generator, maybe even a maze solver. – ghosts_in_the_code – 2015-10-31T05:32:46.617

26

Swift

Factoid

Swift is a compiled language created by Apple, introduced in 2014 and is meant to replace Objective-C, the first supported language for OSX and iOS. Swift is currently used for iOS, macOS, tvOS and watchOS development. It uses the LLVM Compiler

It focuses on writing less code (compared to Objective-C, which is very verbose) and handling safer types. It features type inference, first-class type functions, closures, optional types, enum associated values and many more.

Swift is REPL, you can make your own idea by trying it on http://swiftstub.com/, or http://www.runswiftlang.com (these sites were shut down), use https://swift.sandbox.bluemix.net/#/repl instead.
Sites keep being closed, use https://www.weheartswift.com/swift-sandbox/.

Snippets:

14

case let(8,x):

In a switch case, this statement is absolutely correct.
That switch must have a tuple with two values. When evaluating the expression, if the first value is 8, it enters the case and fills the x variable with the second value of the tuple so you can access it directly inside the case.

11

/** #YES */

In Swift 2.0, comments can be written in Markdown. This produces a big title with YES as text. It can be displayed with format in the help navigator or quick help in Xcode.

10

var i=10e8

It creates a double value with 1000000000.0 in it. You can even write it like this 1_000_000_000.0. Swift accepts different number notations for scientific or currency purposes. It all leads to the same value in memory, but helps to clarify source code.

9

f(#i:int)

When declaring a function, you have to name the formal and the actual parameter, but sometimes the actual parameter name is already a good formal parameter name. Instead of writing the name twice at declaration func myFunc(aMarvelousInt aMarvelousInt: int) you put a hash symbol in front of the parameter func myFunc(#aMarvelousInt: int).
This feature has been removed from Swift 2.0 because it's the default behavior. To prevent using the variable name as a method label, insert an underscore and a space before the variable name func myFunc(_ aMarvelousInt: int)

8

Array<T>

Swift have generics, you can only insert objects of the specified type. The short notation of that array is [T]. In case you want to insert different types in an array, you must specify the type AnyObject, or Any if you don't insert NSObjects inside.

7

let π=3

This declares a constant π containing a approximation of pi. In Swift, source code is in Unicode. Your variable names can even contain emojis .

6

"\(i)"

This returns a String with the value of i in it. The backslash escape character followed by a value in parentheses evaluates the content and inserts it in the string, or if it's a printable object, it uses its description.

5

(3,7)

This is a tuple with two integers. Tuples can be used to make functions return several values. To get the values, you specify the index. (3,7).1 returns 7. You can also name the values at declaration and access them with an identifier. (hours: 12, minutes: 46, meridiem: "PM").minutes returns 46.

4

func

That's the way to declare functions. A function is a first class object.

3

let

That's the way you declare constants. Constants have an optimisation in the compilation phase compared to the var declarations. An example is let hoursInADay = 24.0. Type inference makes that constant a Double.

2

..

This was the operator for half opened range in Swift 1.0, but to avoid ambiguity with the closed range operator ..., it has been replaced with ..< in Swift 1.1

You can use them in for loops (for x in 0..<5), on in switch cases (case (0..<5): break)

1

;

All Semicolons are facultative, until you put more than one instruction in a line.

Crazyrems

Posted 2015-01-19T12:36:59.320

Reputation: 363

I didn't realize that Swift is a compiled language. Is it JIT compiled? – Alex A. – 2015-02-24T19:23:30.293

I think it's not JIT compiled. – Crazyrems – 2015-02-24T21:13:03.340

Huh. Looks like you're right. For some reason I thought it was either JIT compiled or interpreted. Whatever. +1 from me the other day, keep 'em coming! – Alex A. – 2015-02-24T21:24:05.340

@AlexA. It really looks like an interpreted language! For a long time, whenever I saw Swift code I'd think "This code will be slow," even though Swift is very fast. – NobodyNada - Reinstate Monica – 2015-07-22T19:08:22.183

In fact, Swift has a JIT compiler so you can use it as a scripting language, but initially it's designed to have static typing. – Crazyrems – 2019-02-05T09:50:09.300

26

Jelly

Factoid

Jelly is inspired by J and, in particular, its trains. Everything in Jelly – including literals – is a link (function), and you can combine several links by simply chaining them together.

As a tacit language, Jelly programs usually do not require variable references. Also – like J – many of Jelly's atoms (built-in functions) vectorize automatically. This makes Jelly fairly competitive in code golf competitions.

Length 1

b

This full program is a neat little base conversion utility. It takes an integer n as left and a base k as right argument (resp., first and second command-line argument) and converts n to base k.

Now, since integer-to-base conversion only makes sense if both arguments are numbers, the atom b vectorizes with depth 0, meaning that it "searches" for corresponding numbers in b and k.

For example, [n1,n2] b [k1,k2] converts n1 to base k1 and n2 to base k2, while [n3,n4] b k0 converts both n3 and n4 to base k0. Moreover, the list don't have to be rectangular. Combining the two previous examples, [[n1,n2],[n3,n4]] b [[k1,k2],k0] gives the same results as before.

Try it online!

Length 2

»\

Aside from atoms, Jelly has quicks. While a few of them are similar to atoms and simply execute some code, the vast majority affect the behavior of one or more atoms to their left.

For example » on its own is a dyadic atom that returns the maximum of two numbers. The quick \ pops the link » from the current chain and pushes the quicklink »\ in return, which performs a cumulative reduce by maximum, i.e., it computes the cumulative maxima of a list of numbers or characters.

For example, [n1,n2,n3,n4] »\ computes max(n1), max(n1, n2), max(n1, n2, n3) and finally max(n1, n2, n3, n4), and returns the list of all four results.

Try it online!

Length 3

+×_

Any chain of links is parsed in a particular fashion, which depends both on the arities of the involved links (i.e., the number of arguments they expect) and the arity of the chain (i.e., the number of arguments passed to the chain).

If the above full program is executed with two arguments a and b, sum, multiplication and difference are all dyads, +×_ becomes a dyadic fork; the outmost links are evaluated first, then the inner link is called on both results. In this particular example, the result is (a + b) × (a - b) = a² - b².

Try it online!

If the program is executed with a single argument c, each of the links in +×_ is a monadic hook, meaning that is gets called with te previous return value – initially the input argument – and the input argument. Our example thus computes ((c + c) × c) - c = 2c² - c.

Try it online!

Length 4

’!²%

This full program – intended to be run with a positive integer (or a list of positive integers) as sole argument – is a primality test based on Wilson's theorem, which states that an integer n > 2 is prime if and only if (n - 1)! ≡ -1 (mod n).

Since (-1)² = 1 and (n - 1)! is divisible by n is 1 or composite, ((n - 1)!)² % n is 1 if n is prime and 0 otherwise.

The code consists of three monadic atoms (decrement, factorial, square), which are parsed as atops (i.e., they are applied one after the other, each on top of the previous one), and the dyadic modulus – a hook – which gets called with the previous return value and the original n as left and right arguments.

Try it online!

Length 5

“wat»

Jelly has built-in string compression. While it has a few limitations – only produces printable ASCII and only compresses dictionary words – it performs rather well under these conditions.

The characters between and » are replaced with their indices in Jelly's code page, which are then interpreted as the as digits of a bijective base-250 number. In turn, this number arithmetically encodes either an index in the dictionary of short or long words, or a single printable ASCII character.

All arbitrary sequences of Jelly's code page's characters decode to something; the example string wat is decodes to the following.

 stickup Aachen

Try it online!

To compress strings, you can use this script by @Lynn.

Dennis

Posted 2015-01-19T12:36:59.320

Reputation: 196 637

14Where are the more snippets? – CalculatorFeline – 2016-05-07T14:57:57.170

25

Groovy

Length 17 snippet

import bob as Bob

An import alias. No need for fully qualified names on name clash.

Length 16

@CompileStatic()

Another AST. Since it's a dynamic a language, Groovy may run slightly slower than Java. This isn't usually a problem, specially when working with databases and network, but bottlenecks may happen. Enter @CompileStatic. This AST walks the tree representation and makes every call a more pure bytecode call, giving Java-like performance to your Groovy code. Here only Extensions and AST metaprogramming work. You can add it to a class and have it fully statically compiled, and have a single method of this class being dynamic using @CompileStatic(SKIP).

Length 15 snippet

No ideas.

Length 14 snippet

{}.setDelegate

Every statement written inside a closure bears an interesting property: you can change the object which will respond to them. Also you can set the resolving order of responding objects. The topic is lengthy and i won't go over details, but this is possible:

c = {
    gimme "wot!"
}

c.delegate = new Expando(gimme: { it }) // this guy will answer the 'gimme' call
c.resolveStrategy = Closure.DELEGATE_FIRST

assert c() == "wot!"

Length 13 snippet

s ==~ /^echo/

This snippet shows the (unofficially named) dynamite operator and a variant on string declarations. Groovy has a lot of ways to declare strings; 'simple-quoted strings', "double-quoted-with-interpolation-string", """multi-line string""" and what not. But those two stand over the crowd when it comes to regex: /slashy string/ and $/dollar-slashy-string/$. No need to escape stuff, yey: /\d+/!

Length 12 snippet

@TypeChecked

This is an AST Transformation. It walks on the class/method where it is annotated and checks for typing errors. Groovy was born as a pure dynamic language, although you could add types to method params and return. Later on, a lot of people coming from a Java background felt the terseness of Groovy was great, but the dynamic typing was not so, thus @TypeChecked was born. It will still allow Groovy's neat syntax, extensions and other compile-time metaprogramming to occur, but it will report errors on stuff unknown at compile-time.

Length 11 snippet

10.0 * 12.0

Oh, a mere float multiplication, you say? O noes. A digit-dot-digit in Groovy defaults to a BigDecimal, for arbitrary precision calculation. A must for financial calculations. Since operators are only allowed in Java using primitives (and something in String), using a lot of BigDecimals in Java can get messy; this snippet can be written in Java as new BigDecimal("10").multiply(new BigDecimal("20")). For floats, add an f: 10.0f, a d for double, a g for BigInteger, and a lot more.

Length 10 snippet

.metaClass

Every object in Groovy has this little property which is responsible for keeping up the MOP (Meta Object Protocol), which allows Groovy's metaprogramming: we can add methods, properties and even mix entires classes one into another to add functionality. It really shines when you are working on pure dynamic Groovy, but it is not limited to.

Length 9 snippet

a?.b?.c.d

The safe navigation operator. It stop navigating on objects which might be null. This won't throw a NullPointerException if a or b are null, but c must not be null.

Length 8 snippet

"a".tr()

The a object is a java.lang.String, but tr is not a method on Java's String. So what is going on here? Groovy features an Extension Mechanism. When the runtime finds an extension declaration in the classpath, it is automagically added to classes to enhance them. Extensions are statically compilable.

Length 7 snippet

[:]+[:]

Although the term is on pretty gray area, Groovy is a strongly typed language; the runtime makes little or no conversions between types. This snippet is really calling a well-defined method, which you can override, if needed. It can be understood pretty much as new HashMap().plus(new HashMap())

Length 6 snippet

a b {}

This snippet is parsed differently from snippet 5; from right to left. A method a receives the result of a method b receiving a closure/lambda as a param. Curly brackets {} is a closure/lambda/function, in Groovy.

Length 5 snippet

u w m

We can omit a lot of punctuation, as long as we remember Groovy's parsing order. This snippet is understood as u(w).getM().

Length 4 snippet

a*.b

The spread dot allows calling a method, or getting a property, from any iterable. This snippet is collecting the property b from every object in the list a (assuming it is a list).

Length 3 snippet

<=>

The spaceship operator! Calling this is akin to calling the compareTo method. Also chainable with Elvis: price <=> other.price ?: name <=> other.name

Length 2 snippet

?:

The Elvis operator (tilt your head sideways to see it ;-) ). Every class has an asBoolean() method. Elvis calls it (in a deep mississipi voice) and, when true, returns the value, otherwise, the else part. Checking an empty list? Easy: list ?: [1, 2, 3]

Length 1 snippet

&

An and operator. Groovy supports operator overload, but in a slightly safer way: they are overloaded through their names and only a subset of them is available. You can overload the & operator by implementing a method called and(param) in your class.

Factoid

Groovy is an alternative JVM language. It features AST Transformations, i.e., it is possible to walk the tree representation of the code and make whatever changes you'd like to it.

Will Lp

Posted 2015-01-19T12:36:59.320

Reputation: 797

4Needs more ?. since that is just the best thing ever. Well, perhaps after Elvis, which you've already got. – KRyan – 2015-01-20T22:08:00.967

25

Rebol

All the examples below work verbatim in Rebol 3. Just type them into the Rebol 3 console (REPL) and see an immediate result. Obviously for example 14, if file.txt isn't present then it will throw an immediate error :)

25

find "foobar & baz" "bar"

This returns - "bar & baz"

find works on a series returning either a series where it matches or none if no match was found.

Some other examples:

find "foobar & baz" "boo"              ; none
find ["foobar" "bar" "baz"] "bar"      ; ["bar" "baz"]

24

random/only words-of lib

This returns a random word from the Rebol lexicon :)

lib is an object containing all the words defined by Rebol and also any created when importing modules. words-of returns a list of all the words within an object. random/only then picks one word at random from this list.

23

f: function [n] [n * 2]

This creates a new function called f which takes one argument and doubles the value received (the last expression evaluated is automatically returned by the function).

There are a few different function generators in Rebol to choose from. For eg:

  • function - all variables created within block are local

  • func - all local variables must be declared with /local refinement

  • does - has no arguments or local variables.

See Functions chapter from the Rebol/Core User Guide for more info.

22

reduce [1 + 2 * 3 red]

The reduce function evaluates multiple expressions and returns a block of results. There are two expressions in the above block so it returns a block with two values: [9 255.0.0]

NB. For the eagled eyed who were expecting 7 from 1 + 2 * 3 this is because Rebol has no operator precedence and simply evaluates operators from left to right. Use parenthesis to enforce precedence, for eg. 1 + (2 * 3) would return 7.

21

compose [blue (blue)]

This returns a block with [blue 0.0.255]

The compose function evaluates any code found in parenthesis (paren! datatype) but leaves everything else untouched.

20

red + blue = magenta

This returns true because Rebol supports tuple arithmetic.

19

type? baz@email.com

Use type? to find the value's datatype. This example returns email!

NB. As you can see from the examples so far, Rebol comes with a lot of handy datatypes

18

$0.1 + $0.2 = $0.3

The above returns true because these are money! datatypes. So ideal for high precision arithmetic original link down at moment .

17

<div class="red">

This is a tag! datatype.

16

24:00 - now/time

This returns how long there is left in the day (in HH:MM:SS - a time! datatype).

NB. This code shows the first example of a refinement! in Rebol. With refinements you can modify the functions behaviour including adding extra arguments. By itself now would return the current date and time (date!). The /time refinement causes now to return the time only (time!).

15

{"a" {foo} "c"}

This is one way to represent a string! datatype in Rebol. Another way to express this would look like this "^"a^" {foo} ^"c^"" which isn't as visually appealing!

NB. Using braces over double quotes allows spanning of multiple lines and also nested {}. The ^ is used to escape the quoting delimiter. So {closing brace is ^} opening brace is ^{} would be how an unbalanced {} would look.

14

read %file.txt

This will read in the entire contents of file.txt into memory. Any word prefixed with % is a platform-independent file! datatype.

NB. read can also suck content down from other sources, eg. read http://www.rebol.com (this is a url! datatype).

13

100'000'000.0

This is the same as 100000000.0. Single quotes (') are allowed to split up numbers for readability.

NB. Commas can also be used to mark decimal places, eg. 100'000'000,0 is a valid decimal! datatype.

12

something: 1

This sets the word something to represent the value 1.

NB. Rebol is quite liberal in what can be used for a word as long as it doesn't clash with any known datatype. For e.g. another valid 12 length answer would be a-.+!&'*?: 1

11

12-Dec-2012

This is a date! datatype.

10

to-hex red

Functions in Rebol have fixed arity. The to-hex function expects one argument and returns a hex issue! datatype.

NB. The example given returns #FF0000 which is ideal for CSS colours.

9

#{FF0000}

This is hex (base-16) literal notation. Other bases for this binary! datatype are also available.

8

12:15:33

This is a time! datatype (HH:MM:SS).

7

newline

Gives Rebol's internal (platform-independent) newline character. Written as a character literal, this would be #"^/" -- the line-feed character.

NB. The # prefix here denotes a single character and not a string (ie. a series of characters like "foobar"). And the ^/ is Rebol way of representing the control code for LF.

6

speed?

Returns simplistic (and approximate) speed benchmarks for evaluation, CPU, memory & file IO. Handy for comparing the speed of your Rebol on different machines.

NB. General convention is that postfixing word with ? is used to signify what's / what is its. For eg. length? list or type? word

5

1 = 1

Equality test.

The operator = is infix synonym for equal?. == for strict-equal?.

NB. Spaces are important because 1=1 would be recognised as a word (and an invalid word at that).

4

why?

Explains the last error (that occurred) in more detail. It does this by opening your web-browser on the necessary webpage that documents the error.

For eg. foobar would produce the error ** Script error: foobar has no value. Typing why? next will open browser window pointing at http://www.rebol.com/r3/docs/errors/script-no-value.html

NB. This is the first function call example given. why? is a word which points to a defined function (source why? for details). When Rebol interpreter hits a word like this it invokes the function. If the function requires any arguments then Rebol evaluates the necessary words that follow and passes them to the function.

3

red

This returns a tuple which in this case is a tuple of RGB values (for the colour red!).

NB. And red is not the only colour defined in Rebol - http://rebol2.blogspot.co.uk/2012/03/color-names.html

BTW. Red also happens to be the name for an alternative version of Rebol - http://www.red-lang.org/

2

no

Rebol comes with a few synonyms for true and false... yes no on off

NB. These are all just words in the Rebol lexicon (including true & false) so all can be redefined. So if you peek underneath you'll find the truth is actually #[true] (literally!).

1

;

Everything after a semicolon to end of the line is ignored by the Rebol interpreter.

NB. Space(s) are important to Rebol because it interprets the words it sees. But ; is one of those exceptions where it cuts across this.


Factoid

Rebol is a dynamic programming language designed by Carl Sassenrath with data exchange in mind. NB. Douglas Crockford has cited Rebol for being an influence on JSON design.

It had been proprietary but Rebol 3 was finally opensourced on 12-12-2012 just before the world ended :) (according to the Mayan calendar!)

draegtun

Posted 2015-01-19T12:36:59.320

Reputation: 1 592

I'm sad this language isn't indev :c – cat – 2016-03-17T21:05:55.013

1

@tac - Good news... it is "indev" :) See Ren/C which is a community fork of Rebol. In time this (or bits of it) will be fed back into mainline Rebol - https://github.com/metaeducation/ren-c

– draegtun – 2016-03-19T10:04:33.457

25

Awk

Factoid

Awk is a pithy programming language oriented toward string manipulation that also happens to be part of the POSIX standard set of utilities. Awk is named after its original authors, Alfred Aho, Peter Weinberger, and Brian Kernighan. Awk is often used in a pipeline, but large programs have been written in it (pdf, 127KB), too.

0 Characters

Nothing in life is free: an empty awk program prints nothing and exits successfully. (And seems to be the only awk program that doesn't read standard input.)

1 Character

1

An awk program consists of patterns and actions. Omit the action and awk assumes { print }. The above pattern is always true, so awk behaves exactly like cat.

Divergence: Some versions of awk, such as Kernighan's One True Awk consider both the empty string input and the always-true pattern illegal. POSIX says

Either the pattern or the action (including the enclosing brace characters) can be omitted.

So it comes down to whether or not 1 can be considered a pattern.

I'll try to rationalize the divergence between different versions of awk as long as I get more upvotes.

2 Characters

$3

The above pattern is true if the third field has value. If it does, awk will print the whole line. Thus, as a whole awk program, the above will filter all lines that have fewer than three fields.

Once again, the One True Awk does not consider $3 a pattern.

3 Characters

int

BSD treats the above as int($0) and prints every line that can evaluate to a nonzero integer.

Most other awks I tried, including GNU awk consider this invalid. POSIX categorizes int as an arithmetic function and says what it does when invoked without parentheses is undefined.

4 Characters

NF<4

This pattern causes Awk to print those records that have fewer than four fields in them. All editions of awk I tested behave consistently.

5 Characters

/foo/

Boring though it may be, it's time to introduce actual regular expressions. This one will match any line containing the string "foo". This is Awk's bread and butter, and also why it's fairly unnecessary to combine awk and grep.

6 Characters

$NF=NR

This expression overloads the assignment operator = and assigns the number of the current record (row) to the last field. Treating assignments as booleans has the same caveats you might expect from another language. For example $NF=NF would set the last field value to the number of fields, but would skip empty rows.

7 Characters

!(NR%2)

Will print out every other row. It will print the odd ones. I could have written NR%2==0 in the same number of characters, which is more flexible because I could also write NR%2==1 to get the complementary set of rows. I just picked the most obscure syntax because code golf.

8 Characters

!s[$0]++

is one of my favorite Awk expressions. The first time it sees a line it prints it. It never prints the same series of characters again. It's the tersest stable, sort-free uniq I know.

9 Characters

{print$3}

Print the third column. This is one of those boring, but important, Awk "fundamentals" that hopefully opens the door for cooler things with more characters. It's also our first action. (Remember from 1 Character that Awk programs are made up of series of patterns and actions.) Everything heretofore has been just patterns.

13 Characters

FNR<3{print}

Prints the top 2 lines of each file argument. Obviously the print command is redundant, but there were already examples of shorter code. FNR is the line/record number of the current file; whereas NR represents the total number of lines/records processed from all files.

14 Characters

BEGIN{FS=","}

The BEGIN pattern is true before any files have been processed. FS is the field separator pattern used to divide a line/record into fields. This line assigns the field separator before the first file is processed. It is equivalent to executing a script with the command-line argument of -F, with the benefit of not being required to remember to add the argument when running the script.

15 Characters

END{print FNR}

Prints the number of lines/records in the last file read. The END pattern is true after all input has been read, similar to wc -l

kojiro

Posted 2015-01-19T12:36:59.320

Reputation: 717

1An even shorter way to do {print$3} (9c) is $0=$3 (5c), which has the added benefit of not printing blank lines when there is no third column. It also won't print when that third column is numerically zero; to do that, convert it into a string via $0=$3"" (7c). – Adam Katz – 2015-08-29T02:01:39.960

@AdamKatz Just assigning $0=$3 isn't enough to print it. You also need a nonzero label, e.g. {$0=$3}1 which is 8 characters, and there's already an 8 character answer. :( Oops... I see what you were getting at. You are using $0=$3 as the label. Nice. – Robert Benson – 2017-04-11T13:56:42.087

1@RobertBenson – Yup! echo "1\n2\n3 4 5\n6 7 0 9\n10" |awk '$0=$3""' will give you 5 and 0 (using mawk 1.3.3) – Adam Katz – 2017-04-11T19:36:36.030

The 13c option could merely be FNR<3 (5c). I'm not sure why the 15c item uses FNR to count just the last file. Why not use NR and count the whole thing (like the total in wc -l but without the breakdown)? That would make it a 14 char example (which is far better than the current 14c example which is 11c more than -F,). (The per-file breakdown would require 80 chars: NR!=FNR{print --NR,f;t+=NR;NR=1}{f=FILENAME}END{print FNR,f;print t+FNR,"total"}) – Adam Katz – 2017-04-11T20:03:12.557

Feel free to edit my answer as long as it's in the spirit of the "question". (IOW this isn't a code golfing challenge.) Some longer awk would be interesting. – kojiro – 2017-04-11T21:21:55.547

25

Smalltalk

Smalltalk has five keywords. The entire spec fits on a single sheet of paper.

Smalltalk is a small language ;-), with only a minimum number of builtin semantic features - basically the language only defines the syntax for how messages are sent to objects (that's what others would name "virtual function calling").

However, it comes with a big class library. This is open for inspection and extension, and includes everything from numeric operations to UI frameworks to compilers, editors, debuggers and class browsers.

Smalltalk is pure object oriented, with no exceptions. Everything down to integers, characters, stack frames, methods and closures is represented as an instance of a class. This includes classes themself, which are instances of a metaclass.

Every class can be extended, modified, subclassed or reinherited at execution time.

Every Smalltalk dialect comes with a powerful IDE, which makes heavy use of the above dynamic possibilities. For example, it is possible to change code in the debugger and proceed execution without any limitation. Programs are developed inside the IDE - that means that your application classes and objects live in the same world. There is no required separation between the IDE objects and the application objects, and each can make use of the other. of course, you can also extent the IDE itself, while you are living in it.

For programmers, the combination of powerful IDE and high dynamics due to the very late binding, make this a great environment for rapid development.

Length 1

Numbers evaluate to themselves - numbers are objects:

1

Length 2

Character literals (constants) are preceeded by dollar signs:

$1

Length 3

Strings are in single quotes, like in SQL:

'1'

Length 4

Literal arrays are stored in hash & parenthesis. These are created when a method is compiled, not at runtime, so it can improve performance:

#(1)

Length 5

Mixed mode arithmetic is done transparently. Values are coerced automatically as required:

1+2.0

Length 6

Blocks are anonymous functions. They can access the variables in their static scope. Blocks can outlive the dynamic scope in which they were created (i.e. they are Closures). Here is a simple block which returns its argument:

[:a|a]

Length 7

Smalltalk has builtin support for Fractional numbers. These compute exact values and thus avoid the usual floating-point rounding errors. Multiplying 1/3 by 9 gives an exact integer 3, not 2.9999999 as in some other languages:

(1/3)*9

Length 8

Scaled Decimal (FixedPoint) numbers are perfect for monetary values. They will print out with the specified number of fractional digits. Technically, they are fractions with a power-of-10 denominator. The following is a fixedpoint constant which always prints itself with 2 digits after the decimal point:

105.12s2

Length 9

In Smalltalk, assignment is done with ":=". The "Value comparison" operator is "=", as opposed to the "Identity comparison", which is "==". The following will assign a boolean true or false to b, depending on the numerical value of x (i.e. works for x being of ANY numeric type, such as Float, Int, FixedPoint etc.)

b:=(x=10)

Length 10

Intervals are collections, and as such can be used whereever other indexable collections can be used. For example, they can be enumerated with the "do:" messsage, passing a block like shown above; i.e. "(1 to:10) do:[:x |...]". The following creates an Interval representing the integer numbers from 1 to 10.

(1 to:10) 

Length 11

In Smalltalk, statements are separated by a period - just like in English. I added a space, to get 11 characters:

a:=0. b:=1.

Length 12

There's no real syntax for method definitions. You can create methods dynamically, but that takes a lot more chars to demonstrate. This is what you could see as a method definition in a class browser:

+ s
^self, s

This is a binary method called "+", that takes an argument "s". And it returns (^) the concatenation of the receiver with the argument.
Define it in class String to instantly uglify the language!

Length 13

This used to be 100 factorial, but that impresses nobody...

999 factorial

Open a browser, type it in and print it (alt p in Squeak/Pharo), don't be scared. I wonder if it's right though? Probably is...

Just to be sure:

999 factorial / 998 factorial

Squeak says it's 999

John Borden

Posted 2015-01-19T12:36:59.320

Reputation: 351

Please add a factoid that tells something about the language. – NinjaBearMonkey – 2015-01-27T16:19:30.057

2The entire Smalltalk language spec fits on a single sheet of paper (5 keywords). – John Borden – 2015-01-27T18:44:30.283

4Are you going to add snippets now? – Scimonster – 2015-02-04T08:42:25.180

Also, about length 11, in Smalltalk period separates sentences. In English period ends them. It's a bit of pedantry, but it's the same difference between C and Pascal, for instance (where it's more relevant) – fede s. – 2016-04-04T19:19:32.897

25

dc

Almost nine months later -- I can't believe dc is not on the list!

Factoid

dc (desktop calculator) is a Unix utility older than the C programming language, and also the hardest programming language to google. Luckily it's probably preinstalled on your Linux, Unix or Mac box, and available for Cygwin too!

Length 1

1

dc is a stack oriented language. 1 is an instruction that pushes the number 1 one the stack so that we can use it for other instructions.

Length 2

?f

These two characters is a whole dc program that actually does three things! It takes a line of input, evaluates the input as dc code, and prints the contents of the stack afterwards. You can feed it with the next snippet that I will post if I get another vote :)

Length 3

zzp

z pushes the current stack depth. Initially the stack is empty, so 0 is pushed on the stack. The stack is then 1 deep, so the next z pushes 1. p prints the top of the stack, which at this point is 1 (although the stack depth is now 2 :D).

Length 4

1A0F

dc supports number input to be in any base from 2 to 16, so the characters 0123456789ABCDEF all work as digits. Input numbers are not limited to only digits found in the current radix, but they still respect the positions of that base. This means that in base 10 (which is the default), the given snippet evaluates to 1*10^3 + A*10^2 + 0*10^1 + F*10^0 = 2015 :)

Length 5

O[P]x

A convoluted way of printing a newline! O pushes the current output radix (which defaults to 10 and is independent of the input radix). [] defines a macro and pushes it. x pops the macro and executes it. P pops and prints a value as a byte stream.

Length 6

[dx]dx

Duplicate and execute, duplicate and execute, rinse and repeat. One copy of the macro is always left on the stack, so this loops forever. On some systems or implementations it may crash.

Length 7

[]sf7>f

This is sort of an if-statement: It will execute the empty [macro], which is first stored in register f, if the top of the stack is less than 7. Intuitive, huh? Just wait for an if-else! I will need way more characters for that though ;)

Length 8

3812649P

Prints a smiling face :-) Another example of the P command. 3812649 is the character points of the smiley string shifted to their correct position in base 256 and added together. Very useful technique for creating quines and quine-like programs.

Length 9

[9<L]dsLx

This is kinda the standard template for a loop -- 9 can be replaced with any code, and you can use other comparisons than <. As the snippet stands now though, it is perhaps not the most useful thing in the world:

The comparison consumes one element in addition to the 9 that is pushed every time, so the snippet will pop each element down to, and including, the first element which is less than or equal to 9. If it were to empty the stack, the last comparison would fail with a warning, and leave the 9 on the stack.

Length 10

6581840dnP

If I had actually counted how few characters it takes beforehand, I guess I wouldn't have ruined the surprise just two snippets ago, but yeah... this is a quine.
(That means that the program prints out its own source code)

Length 11

I just came up with this for the dc golfing tips post, and I'm quite excited because I'm absolutely sure that this is the shortest possible way to write an if-else-statement!

Suppose you want to do if top-of-stack == (THAT) then (THEN) else (ELSE)

[[(THEN)2Q]sI(THAT)=I(ELSE)]x

Uses the I register. The placeholders (THAT), (THEN) and (ELSE) isn't part of the byte count, and = can of course be exchanged with any of >, !>, <, !<, !=.

daniero

Posted 2015-01-19T12:36:59.320

Reputation: 17 193

24

Powershell

Factoid:

As part of Microsoft's "Common Engineering Criteria" Powershell is designed to provide an automation platform and unify the management experience across all MS Server products. It leverages both the command line strength of a robust shell and the object awareness of the .NET infrastructure.

To handle a highly complex environments the standard naming convention for Powershell commands and functions follow a Verb-Noun structure (ex. Get-Help). This means that in favor of clarity and readability long names are actually encouraged. However because this is a "working admin's shell" there are 2 tools that keep this from being a burden. The first is "tab completion" for commands, parameters, filenames, etc. The second is a robust alias structure, many of these examples will feature aliases.

Length 1

|

Pipe Piping is a common feature in Shells. Powershell improves on this by piping objects instead of strings. So if (for example) a command selecting a file is on the left side of the pipe, then all of the complex attributes {Full path, directory, CreationTime, etc.} of that file are available on the right side of the pipe.

Length 2

gm

gm is an alias for Get-Member which presents the various properties and methods that are available for an object. The most common of usage will be following a pipe. Using gm on a file reveals 24 methods and 21 properties native to the System.IO.FileInfo object type. gm is one of "the 3 things that reveal everything in Powershell" if you know only these 3 things you can use them to discover every function available.

Length 3

gci

gci alias for Get-ChildItem (other aliases are dir and ls). In it's simplest sense gci retrieves the contents of a directory; you can apply filters, selectively recurse, and do everything that the DOS and Bash equivalents can. The real power though is that Get-ChildItem has the ability to navigate "Powershell Providers." Providers exist for Environment Variables, the Registry, Certificates, and VM datastores; meaning that once you connect to the provider you can browse and interact with these abstract environments using familiar command-line navigation and logic.

Length 4

help

help alias for Get-Help, and the second of "the three things that reveal everything". Help reveals structure, syntax, and function. For "professional" cmdlets and modules examples will be included. However help is dynamically aware of what's going on, so even for the most slapped together amateur functions you can use get-help to see the basic parameters and syntax.

Length 5

h |fl

This is the first example that is not just a component but is actually full, complete, and practical in daily usage without any further parameters or modifications.

h alias for Get-History. Session History automatically logs your commands, and you can bring up recent commands with the up arrow. However to get a complete picture of command history use Get-History to present this array of information.

| pipe, in this case we are piping an array of HistoryInfo objects. (note: space before or after a pipe is optional... but it sure makes examples more readable. So this could also be a length 4 example. Working from the command line I tend to insert a space before as an old habit.)

fl is an alias for Format-List. Commands beginning with Format- are display options, no data is manipulated. Format-List accepts the piped input and displays the properties (for each array item) as a separate line. This helps to quickly expose statistics like ExecutionStatus, StartExecutionTime, and EndExecutionTime for each history item.

Length 6

(h)[0]

This is a very simple demonstration of some complex concepts.

h as we've already covered is an alias for the Get-History Cmdlet. This Cmdlet returns an array of objects.

( ) brackets in an expression like this work like in a math formulas, you process what's inside the brackets to get the result before other operations are performed. So by using (h) or (get-history) we are designating that things outside the brackets will not be interacting with the command itself, but with the resulting array.

[0] this shows a way of directly specifying one element within an array, following standard comp-sci usage 0 represents the "first" element in that array. This example returns element 0 of the array returned by (Get-History). This can be useful when you want to systematically retrieve the Nth element of a sorted array, change the Nth letter of a string, or change the Nth octet of an IP address.

Length 7

-Whatif

-Whatif is a "common parameter" enabling a safety routine within Powershell. Get-Help states: "When a cmdlet supports WhatIf, the cmdlet reports the expected effect of the command, instead of executing the command."

So if you have generated a list of files stored in the variable $deletePending and your next step is to run $deletePending | Remove-item if you want to make sure that a typo isn't going to ruin your week you can run a simulation of that command $deletePending | Remove-item -whatif Each simulated step will output a line similar to:

What if: Performing operation "Remove file" on Target "C:\folder\file.tmp".

You can also turn WhatIf on for an entire session if you want to do extensive testing. Most native "danger zone" cmdlets support the WhatIf parameter, and support can be integrated into your custom functions.

Length 8

if(h){h}

This demonstrates the logical flow "IF the statement inside the brackets resolves to a Binary True, then run the statement in the curly brackets." It's important to understand that a Binary True ($true) can be achieved in multiple ways. Some examples:

if ($True)        if (1 -eq 1)        if (Get-Date)       if ("False")

That last one surprises people sometimes; but it's strong logic, "False" is a valid string and no valid string will ever equal Boolean False ($false).

In the 8 Length demo, the test being evaluated is "does (Get-History) return $False?"

if ( h ) { h } will return $false if you run it in a brand new session, run it a second time and it will return $true because now a history item exists. Being able to evaluate using cmdlets and functions can be very powerful, as long as you understand if and when a $false can be returned.

Length 9

-computer

This parameter exists for cmdlets that support "implicit remoting" (such as get-process, stop-process, get-service, get-eventlog ). Generally speaking if you could do it through the management GUI or some form of WMI request you can now automate it through Powershell Cmdlets.

Length 10

get-acl c:

If you have a file sharing structure then 1 of 2 things is true; either you need to "clean up the permissions one of these days" OR you've automated your standards.

In both cases get-acl and set-acl are better than the tools you've had before.

This is another tool that leverages powershell providers so it's just as easy to work with the ACL of HKLM:\Sofware\ExampleSoft as it is with C:\Program Files\ExampleSoft. Build a few scripts around the custom installs in your environment and you'll never grant "Local Admin" to a user again.

Length 11

Get-Content

"Gets the content of the item at the location specified by the path, such as the text in a file. It reads the content one line at a time and returns a collection of objects , each of which represents a line of content."

Any good shell better be able to read a file's contents, so why is Get-Content worth mentioning?

-encoding  -raw  -stream  -delimiter  -readcount  -totalcount  -tail

Examining the parameters we see it can do a lot more than just push stdin to stdout. For example we can pull the elusive Zone ID from the alternate data stream to see whether $file is flagged as originating from a trusted or untrusted zone.

Get-content -path $file -Stream Zone.Identifier

Length 12 - modular function component 1

function f{}

Creates a function named f. Code within the curly brackets will be run whenever f is called.

In case you're wondering, since this is an empty function evaluations of f will find it equals $false.

Length 13 - modular function component 2 (updated)

{my original length 13 was actually 12, so I'm re-working this entry}

$MyInvocation

This automatic variable exists for functions and other script blocks. It contains valuable diagnostic information about how a script block was invoked, including arguments and pipeline status.

If we simply place $myinvocation into our function, calls to f will return the invocation properties.

Length 14 - modular function exploration1

$a=1..5+8
f @a

Running this will return the invocation properties from our function, which you can use to verify the breakdown I'm providing here.

This demonstrates populating a variable, and then calling our function with that variable as an argument. Since the ';' represents a break in the pipeline this can also be written as $a=1..5+8;f @a

$a = creates (or overwrites) the variable a

1..5 populates $a with the numbers starting at 1 and ending at 5 (meaning that $a has actually become an array of integers).

+8 looks like math, but since we're working with an array of integers this is really adding the integer 8 to the existing array

f since we defined 'f' as a function earlier we can now call it anywhere within the session just by using its name. Best Practice is to name functions following the Verb-Noun convention. Since function names are automagicly candidates for tab-completion do yourself a favor and only use short function names for silly things like code-golf.

@a Here the space separates the function name from it's arguments.

The @ (array identifier) is interesting. If we call f $a then we pass the array as a single argument. By specifying f @a we pass each individual array element as an argument. The function will behave as if called like this f 1 2 3 4 5 8

Length 15 - modular function component 3

$args| %{$_+$_}

If you ran the "Length 14" exploration code you'll see the "UnboundArguments" invocation property, the $args automatic variable contains an array of arguments passed to a function as undeclared parameters.

% is an alias of Foreach-Object, which accepts the piped object and individually submits each element to the following script block { }

$_ contains the current object in the pipeline context.

$_ + $_ since we are in a foreach context our current object is each individual integer in our array, we demonstrate that by adding each Integer to itself. Since the + operator is context aware it reacts appropriately to either integer or array contexts.

Current Module:

Function f{
$myinvocation
$args| %{$_+$_}
}

H.R.Rambler

Posted 2015-01-19T12:36:59.320

Reputation: 331

now that you're at 12 you can show superfluous while loops! h | % { $_ } – KutuluMike – 2015-01-29T23:21:05.400

@MichaelEdenfield nah, all those spaces are optional :-) You mean h|%{$} which is a 7 length. And I'll need 15 to do h|%{$}|? -p id – H.R.Rambler – 2015-01-30T13:57:15.150

24

Lua

Factoid

Lua is a dynamic, lightweight yet powerful, highly portable (pure Ansi C), fast and easy to learn scripting language.
Initially designed to be a configuration language and to be embedded in applications to script them, it is also used as a glue between native libraries and to be a standalone language on its own.

Length 1

;

You will nearly never see a semi-colon at the end of a Lua statement (unless that's the taste of the coder!), as they are totally optional and, most of the time, unnecessary. They can be used if you want to put two statements on the same line (even then it is optional: a = 5 b = 3 is OK (but ugly!)) and to avoid some ambiguity: a = f (f1 or f2)(x) can be seen as a = f; (f1 or f2)(x) or as a = f(f1 or f2)(x) (call of f with a function argument returns a function which is called with x as argument).
The semi-colon can be used as separator in table literals, too.

Length 2

..

That's the string concatenation operator in Lua. If we concatenate a number, it is converted to string. For something else than strings or numbers, the __concat metamethod is called (more on this later).

Length 3

nil

is a special value, whose main property is to be different from any other value... It is generally used to represent the absence of a useful value, equivalent to null in some other languages.
It is the only other value that is "falsy" (the first one being false, of course), any other value is coerced to true in a conditional expression.

Length 4

f's'

The function f is called with the literal string "s". Note that literal strings can use single quotes or double quotes as delimiters.
Here, as a function called with a single, string argument, we can omit the parentheses. That's syntax sugar for f('s'). This can be used for writing some nice DSL.
This syntax shortcut can be used too when the single argument of the function is a table.

Length 5

a={1}

The variable a is assigned with a table with one entry, 1.
Here, the table is treated as an array. We will see they can be also associative arrays (key / value).
Table is a fundamental data structure in Lua, so it is optimized and efficient: it can have both an array part (with fast numerical index access) and a hash part for the associative side.

Length 6

[[\n]]

A literal string (long format) made of two characters: backslash and n. The [[ ]] notation allows to write multi-line strings with no escapes inside. Newlines are kept literally (except the one immediately after the opening bracket, if any: it is ignored for convenience of formatting).
Lua allows nesting of long literal strings (eg. if you want to put one inside another) by putting a number of = sign between the two brackets. Of course, matching closing brackets must have the same number of equal signs.

Length 7

t={k=v}

A table defined as associative array: here, k is a shortcut for ['k'], a string key (the latter annotation is useful for string keys that are not valid identifiers). v is a variable, its value will be the value of the entry.
The key (index) can be any Lua value, except nil. The value can be any Lua value, but nil actually removes the entry.
Access to entries can be done as t.k or as t['k']. The first form is valid only if the key is a valid identifier, otherwise we have to use the second form.

Length 8

a,b=f(x)

A function can return several values (put them after the return keyword, separated by commas), and these values can be assigned at once to several variables.
If the function provides more values than the number of left-hand variables, the extra values are dropped.
If it doesn't provide enough values, the extra variables get nil as value.
A common pattern in Lua is to return either a single value, or nil and an error message if something went wrong.

Length 9

--[[ C ]]

A block comment. Line comments are marked with a double dash. Block comments extends this notation with a block of text (potentially multiline) marked between double brackets. Actually, they use a syntax similar to long literal strings, including the equal signs between the brackets, whose number allows to distinguish nested blocks. This allows to avoid conflicts with other block comments or long literal strings when commenting out a long block of code.

Length 10

local v={}

Lua started its career as a configuration language, and is still useful as such. Because of this, its variables are global by default, ie. they are attached to the built-in _ENV variable and visible everywhere. That's also where we find the standard libraries, for example.
Of course, this global environment is to be avoided for most usages, because of collision risks, encapsulation issues, and because a global variable is slower than a local one.
Lua supports lexical scoping, we can define variables that are visible only within their scope, their chunk (from the declaration point to the end of the chunk) and the nested chunks.
The statement above declares a local variable initialized to an empty table.
For performance reason, a common practice is to bring global functions to the local scope, like local print, find = print, string.find.

Length 11

a,b,c=b,c,a

As seen, a function can return several values, which can be assigned in one go to several variables.
It also works with several values (separated by commas) on the right hand side.
The expression above cyclically permutes the values of a, b and c, ie. a takes the value of b which takes the value of c which is assigned the value of a. It is a variant of the a, b = b, a expression which swaps two values.

Length 12

::L:: goto L

The programming world frown upon the usage of GoTo, but the Lua authors consider it is malevolent only in bad hands... They introduced it in Lua 5.2 to answer a frequently asked feature: adding a continue statement. The goto statement effectively allows to jump to the end of a loop, and also allows to break out of several nested loops. Note that Java, which has goto in its reserved words, doesn't implement it, but have named break allowing such feature...
Here, goto SomeName jumps to a scoped label named... SomeName, which is defined by surrounding the name with double colons like ::SomeName::

Length 13

(a or b){x=1}

This is a function call with a table as argument. Lua allows the syntax sugar of omitting the parentheses around the argument if it is unique and it is a table, similar to the call with a string seen at length 4. It allows to create some nice DSLs...
Here, we also see a logical expression between two functions: if a is defined, it is called with the argument. If it is not defined, ie. has the value nil, then that's b which is called (assuming it cannot be nil). This fallback syntax is idiomatic in Lua to provide default values to variables. It has the same function than the ternary operator of C-like languages (a ? a : b)
Note that in Lua, logical operators are spelled out: or and not instead of C's || && !, slightly less readable for newbies.

PhiLho

Posted 2015-01-19T12:36:59.320

Reputation: 653

As @Benjamin seems too busy to have time to update his entry, I take the liberty to start a new Lua entry, since it is allowed by the rules... I have some snippets ready, so vote up! ;-) – PhiLho – 2015-01-29T09:58:34.727

1Wonderful, I didn't even know you could use [[ ]] for multiline strings in Lua. Lua is rather under-appreciated. – Hugo Zink – 2015-12-22T10:25:28.217

1I love your answers and the information you added to each snippet. Please update, i want to see the other snippets :) – pschulz – 2016-07-25T14:36:06.137

24

Julia

Factoid: The Julia language was created as a fresh approach to technical and high-performance computing. It's free and open source.

Note: Though not a requirement of the competition, every snippet here can be evaluated at the Julia REPL without issue.


Length 7:

@time 1

Julia has built-in tools for profiling code. Among them are @time and @allocated, which are actually macros. Here we're using the former.

From the documentation:

A macro to execute an expression, printing the time it took to execute and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

From the source code (at the time of writing):

macro time(ex)
    quote
        local b0 = gc_bytes()
        local t0 = time_ns()
        local g0 = gc_time_ns()
        local n0 = gc_num_pause()
        local nfs0 = gc_num_full_sweep()
        local val = $(esc(ex))
        local nfs1 = gc_num_full_sweep()
        local n1 = gc_num_pause()
        local g1 = gc_time_ns()
        local t1 = time_ns()
        local b1 = gc_bytes()
        time_print(t1-t0, b1-b0, g1-g0, n1-n0, nfs1-nfs0)
        val
    end
end

So what happens when we time the integer 1 at a freshly opened REPL?

julia> @time 1
elapsed time: 0.000521626 seconds (13880 bytes allocated)
1

13880 bytes allocated to print the number 1?! That seems a little excessive. But as it turns out, most of the allocation is due to the fact that Julia is JIT compiled. (Thanks to Martin Büttner for correcting me on the reason!) But if we were to run this again in the same session, we'd get something a little different:

julia> @time 1
elapsed time: 3.04e-6 seconds (80 bytes allocated)
1

That's much better!


Length 6:

≠(1,0)

What is that blasphemous character?! Those of us used to programming in the realm of ASCII may be initially put off by the presence of non-ASCII characters in source code. But fear not! Julia has your back. You can use a finite set of Unicode characters for input.

The operator is equivalent to !=, i.e. "not equal to". You can write it like ≠(1, 0) as in the snippet, or like 1 ≠ 0. Since 1 is obviously not 0, this returns true.


Length 5:

read!

No, Julia isn't commanding you to get up from your computer and read a book. In fact, read! is a function. In Julia, functions which modify their arguments end in !. In this case, read!(s, a) reads binary data from an input stream s and writes it to an array a.


Length 4:

1//0

Have you ever thought to yourself, "Man, I wish I could store an exact ratio of integers rather than a decimal value"? If so, you're in luck: Julia has a rational number type!

"But wait," you say, "I thought only Chuck Norris could divide by 0." Actually, Julia can deal with infinite rationals such as this one. However, it can't do 0//0... Only Chuck Norris can do that.


Length 3:

3\4

Julia has a built-in function akin to Matlab's backslash (\) operator that performs matrix division using a polyalgorithm. So A\b solves the matrix equation Ax=b for x. When you give it integers, like in this example, it's solving the trivial equation 3x=4, so the result is 4/3 = 1.333333.


Length 2:

im

This is a global constant which represents the "imaginary" number i, which is the principal square root of -1. Julia has a predefined type for complex numbers which supports all standard mathematical operations!


Length 1:

:

This returns colon(). The colon is used to construct ranges, like start:stop (assuming a step size of 1) or start:step:stop. Indeed, : actually calls the colon() function, so 1:4 is equivalent to colon(1, 4).

Alex A.

Posted 2015-01-19T12:36:59.320

Reputation: 23 761

24

Scratch

Oops! I kind of feel like a terrible person for not updating this lately. I'll try to be more consistent with my updates, e.g. when somebody votes I'll update.. Forgive me? :)
Oops! Wow, did it again. A link or two was broken; that should be fixed now.


Scratch is a graphical programming language created by MIT. Because it's graphical and block-based, rather than counting the number of characters, I'm going to count the number of blocks (after all, the number of characters could change with translations).

Rather than getting a screen shot of every single script I'll give you a link to a Scratchblocks page. I'll also post the code for it below.

This answer is in development! ;)

Um, also, maybe read the scripts from bottom to top..? :P


Length 11

Code:

when [space v] key pressed
set [Playing? v] to [1]
set [Score v] to [0]
reset timer

when this sprite clicked
if <(Playing?) = [0]>
  change [Score v] by [1]
end

when [timer v] > (10)
set [Playing? v] to [0]

Well, we've got three whole scripts here! This should be simple enough to understand, but I'll explain it anyways.

when [space v] key pressed
set [Playing? v] to [1]
set [Score v] to [0]
reset timer

When the space key is pressed, we want to set the playing variable to 1 (e.g. true), the score variable to 0 (e.g. no points yet), and reset the timer. The timer is an important part of this project!

when this sprite clicked
if <(Playing?) = [0]>
  change [Score v] by [1]
end

When the sprite is clicked on, if we are currently playing, change the score by 1.

when [timer v] > (10)
set [Playing? v] to [0]

When the timer is greater than 10 (e.g. 10 seconds have elapsed since the timer has last been reset) set the playing variable to 0. Because it is now 0, in the when-sprite-clicked script the score is no longer increased.

By the way, here is the costume that the sprite uses:

Sprite Costume

A key bit of information about this project is that you can have multiple scripts inside a single project. Each of these scripts will be called according to their hat block, so when this sprite clicked will happen when this sprite is clicked on!

Getting a bit technical here, but Scratch does not use multiple threads. Instead you should think of scripts being stuck into a list of things to do. It's a bit complicated but works similarly to the way JavaScript does.

Also, keep in mind that many blocks will automatically update the screen (as well as control events, for example, a loop looping) and will tell Scratch's interpreter to go on to the next script occurring simultaneously. You can get around this by putting your script inside of a run-without-screen-refresh custom block as shown in length 8.

Length 10

Code:

when GF clicked
set tempo to (pick random(30) to (120)) bpm
set [Note v] to [55]
repeat (3)
  play drum (15 v) for (1) beats
end
repeat (10)
  play note (Note) for (0.3) beats
  change [Note v] by [1]
end

This one hopefully won't blow your mind too much. It's a simple melody with a drumroll. I don't think it needs that much describing. ;)

(Scratch Official Editor) (Scratchblocks) Length 9 Snippet:

// Sprite: Cat
when GF clicked
go to x: (-130) y: (90)
point towards [Apple v]
repeat until <touching [Apple v]>
  move (2) steps
end
broadcast [got apple v]

// Sprite: Apple
when I receive [got apple v]
hide

What's so nice about Scratch is that it's scripts are very self-explanatory. I probably don't even need to explain to you what this does for you to figure it out (especially if you run the program by going to the above link).

However, this example does introduce a few new things I haven't shown yet:

  • Sprites: These are Scratch's idea of things in the world (stage). A sprite is generally what you use when you want to add a character to your scene. Whenever you open up the editor, you already get pre-loaded a sprite - it's that scratch cat! You can use as many sprites as you want in your program as well. Learn more about Sprites and how to create them on the wiki.

  • Broadcasts: A broadcast is as it sounds (literally) - it's a message that is sent through the project to every single sprite in the program. You use the when I receive hat to make something happen when a script is broadcasted. Broadcasts are a very important part of the programming language and you can learn more about them on the wiki here.

One last cool thing about this project is that if you change the numbers in the go to x: y: block it will always work - so why not try it?

(Scratchblocks) Length 8 snippet:

when GF clicked
insta

define insta
pen down
repeat (360)
  turn cw (1) degrees
  move (1) steps
end
pen up

Boom - custom procedures! I'd just like to clarify here - this is an instant custom block, or as I and some friends like to call them, atomic procedure. All that means is the block runs in a single frame - which is quite important for turtle graphics!

Here is a screenshot of the script, and the dialog I used to make the custom block:

Atomic Functions

(Scratchblocks) Length 7 snippet:

when GF clicked
ask [Hexadecimal decoder - please type a hex number WITHOUT THE 0x PART:] and wait
say (join [] ((join [0x] (answer)) - (0)))

Oh, hey! Scratch has hexadecimal decoding support! Who would have guessed?* Simply use ((join [0x] [###]) - (0)) to decode some hexadecimal.

(Scratchblocks) Length 6 snippet:

when GF clicked
set [var v] to [0]
repeat (10)
  change [var v] by (1)
  say (var) for (0.5) secs
end

Variables in Scratch are represented by their own orange blocks - to declare one, you press the button Make a variable inside the Data category. This creates a new block, name, in the Data category. To manipulate it, use the variable blocks. All variables also have an (optional) watcher which can be customized - see the watcher's wiki article for more information!

(Scratchblocks) Length 5 snippet:

pen down
clear
repeat (180)
  move (2) steps
  turn cw (2) degrees
end

Here we demonstrate - like all good programming languages should be able to - turtle graphics! Just because Scratch is a visual programming language really gives it just that extra bit of fun when you're programming, even more so with the pen!

(Scratchblocks) Length 4 snippet:

forever
  play note ((timer) mod (50)) for (0.5) beats
end

Scratch has many built in instruments - the simplest way to play a note is via the play note for beats block. Keep in mind the default instrument is 1 (piano) and the default tempo is 60bpm. Using blocks found in the Sound Category you can do things like change the instrument, play sounds you import, and even use the built in drum set!

(Scratchblocks) Length 3 snippet:

when [space v] key pressed
point towards [mouse-pointer v]
move (10) steps

When the space key is pressed, it moves the selected sprite toward the mouse. This makes it easier to demonstrate moving towards the mouse as you don't need to move the script whenever you want to change direction (and it would still only be able to go towards the east edge of the stage).


(Scratchblocks) Length 2 snippet:

point towards [mouse-pointer v]
move (10) steps

When the script is clicked, it moves the sprite ten steps towards the mouse when clicked.

(Scratchblocks) Length 1 snippet:

move (10) steps

When the script is clicked, it moves the sprite ten steps (pixels) in the direction it's facing, which, assuming you're using a non-touched-so-far sprite, will be towards the right (90° in Scratch).


Factoid: Scratch was originally released in 2007 (it was made in very early stages in 2003 or 2002 I believe) and now has over 7 million people using it (Scratchers) and over 10 11 million projects created. It's used all around the world as well. Check out the statistics page to see more stats about Scratch, and try it out online here. It's free!

* The Advanced Topics would. :)

Florrie

Posted 2015-01-19T12:36:59.320

Reputation: 831

Added the second. – Florrie – 2015-07-17T09:52:51.853

Added the third. – Florrie – 2015-07-21T10:01:35.290

oops I suppose I should update this – Florrie – 2015-08-25T19:11:50.607

Added the fourth, fifth, and sixth! – Florrie – 2015-08-25T19:58:51.183

Also added to the language list on the first post. – Florrie – 2015-08-25T19:59:07.273

Added the seventh, eighth, and ninth. Need to keep more of an eye on this.. forgive me? :) – Florrie – 2015-10-12T02:22:14.923

Forgot to say I added the tenth and eleventh. Now I have to add the twelfth. o_o – Florrie – 2015-10-18T19:55:01.393

Don't forget to add #12-17 :D – DJgamer98 – 2015-11-04T14:35:14.403

I'm working on it.. any ideas? :P – Florrie – 2015-11-04T19:59:51.033

@towerofnix Prime numbers? – wizzwizz4 – 2016-10-01T10:48:38.210

Nice conversation down here in the comments! – RudolfJelin – 2016-10-18T16:06:00.910

23

Dart

Length 17:

a.forEach(print);

Dart's first class functions offer concise coding patterns. Here, the print function is called for each element of a. This is the equivalent of the following:

a.forEach((e) => print(e));

Length 16:

a({b: 42}) => b;

Functions can have named parameters by using curly braces. Named parameters are optionally passed in by name by the caller, and can have a default value.

print(a());      // 42
print(a(b: 11)); // 11

Length 15:

int get x => 9;

You can define getters for a class that return a value. By default defined class fields create implicit getters and setters, but you can use the get and set keywords to define explicit custom getters and setters.

Length 14:

'''a$b

 c
''';

Multi-line Strings are created in Dart using triple quotes. String interpolation still works.

Length 13:

typedef C(a);   

You can use the typedef keyword to assign a name to a function type. Here, C defines a function that takes a single argument. Now we can refer to C where we a need a function with that signature:

k(C c) => c;

And calling k:

k((a) => 4);

This is all very similar to the previous snippet, but can simplify things greatly if we need to continuously refer to a function type.

Length 12:

a(b()) => b;

Dart functions are first class. Here a is a function that takes another function as an argument and returns it. You could call a like this:

a(() => 4);

Note that the result of this is not 4, but rather a function with the signature () => dynamic.

Length 11:

int _a = 5;

Dart uses _ as a privacy modifier. Fields and methods prepended with _ can only be accessed in the library that they are part of.

Length 10:

A(this.x);

Dart has syntax sugar in place for constructors that simply set fields. When using this.field in a constructor, the field is automatically set to the passed in argument. The above concise code is equivalent to the following:

A(x) {
  this.x = x;
}

Length 9:

Z.blank()

Dart methods, including constructors, cannot be overloaded. If you want to have multiple constructors for a class, you can use named constructors instead. Using a named constructor is straightforward:

Z z = new Z.blank();

Length 8:

main(){}

The shortest Dart program you can write. Every Dart program requires a main function as an entry point.

Length 7:

a()=>4;

You can use fat arrows for short hand functions. The above code is equivalent to:

a() {
  return 4;
}

Length 6:

a as B

The as keyword allows you to cast an object to any type, in this case the variable a is cast to type B. This is very useful when you know the type of an object returned by a dynamic method and want the tooling to reflect that. For instance, if you were working with HTML and queried the DOM for an element, you could specify the type of the element, even though that type is not actually returned:

InputElement input = querySelector('#someInput') as InputElement;
// Go ahead and use input safely as an InputElement

Length 5:

'A$k'

$ is used within Strings for interpolation. In this example if k was a variable with a value of wkward, the full value of the interpolated String would be Awkward.

Length 4:

true

Unlike other languages such as JavaScript, in Dart true is the only value that is true. The same applies to false. Values such as 0, 1, '', null are not truthy.

Length 3:

var

Var allows a variable to refer to any type of object. Tools will attempt to infer the actual type of the object.

Length 2:

{}

Dart supports map literals.

Length 1:

;

Semi-colons are mandatory to terminate a statement.

Factoid: Dart is an optionally typed language, which means you can add types to aid developers and tools, but they have no effect on your program's semantics - it will run the same whether you add types, or don't, or even add incorrect types.

Pixel Elephant

Posted 2015-01-19T12:36:59.320

Reputation: 333

Can ;, {}, and var run as standalone statements without warnings or errors in Dart? I'm unfamiliar with the language. – Alex A. – 2015-01-20T16:42:23.860

They can't. It will take a quite a bit of characters to get to something that will run, since Dart requires at a minimum: main(){}. – Pixel Elephant – 2015-01-20T16:44:45.407

23

Ceylon

Factoid

The Ceylon name is a play on the Java name (since it is a JVM language, and like many others, it secretly hope to be a better Java). Java and Ceylon (now Sri Lanka) are both islands in the Indian Ocean, one growing mostly coffee, the other growing mostly tea...

Length 1

;

Semi-colons are mandatory in Ceylon, unlike several modern languages. As said in the language FAQ, it is a compromise in syntax.
Note in that languages where semi-colons are optional (JavaScript, Scala, Lua, etc.) but where lines can be split arbitrarily, there are often cases where missing semi-colons can result in ambiguous or unexpected expressions...

Length 2

4T

is a valid literal number in Ceylon. It reads "four tera" and its value is 4_000_000_000_000. Ceylon supports, like Java, digit grouping, and unlike lot of languages, number suffixes from f (femto, e-15) to P (peta, e+15).

Length 3

A|B

is a type which is the union of two disjoint types. This means that the value with this type can be of either A or B type. Since Ceylon does not support method overloading, it allows to define methods accepting various inputs in the same parameter, or various outputs. This feature is great to indicate a value can be null (it can't by default) and to support JavaScript dynamic types.

Length 4

{C*}

Type annotation for a stream of instances of the class C. This stream can be evaluated lazily. That's actually a shortcut for the Iterable<C> type.

Length 5

value

Ceylon is strictly typed, but is able of type inference, ie. you don't have to specify the type of a local variable (or of the return value of a local function) if the compiler can infer it.
You have to spell it out for class fields, function parameters, etc.
So you can declare a local variable with the value keyword in place of the real type, the compiler will guess its type from its assignment. Note that the term "variable" isn't right here, as it will be immutable (the default of local declarations, you have to declare them variable explicitly to mutate them).
I will continue to use the term variable here, even if they are immutable...

Length 6

Float?

Type of a float variable that might be null. By default, Ceylon values cannot be null. We have to declare explicitly if null is possible in the type of the declaration itself. And then, the Ceylon compiler forces us to check if the value is null. Thus, we can never have a NullPointerException, which doesn't exists in the language! It is one of the rare totally null-safe languages (Rust is another one, with a very different approach).
Note that this type declaration is actually a shortcut for Float|Null, ie. as seen above, the union of Float and of the Null type (which has only one instance: null).
Also note that Float is a class on its own, with methods. It is optimized to the Java float primitive by the compiler, though.

Length 7

Float[]

Type of a sequence of float values which can be empty. It is a shortcut for Sequential<Float> and can be written [Float*], similar to the stream / iterable annotation. The difference is that a sequential can be indexed with the [i] notation, like an array. For the record, a Sequence<T> (or [T+]) is a sequential that cannot be empty. An empty sequential has the type Empty and is noted [], of course.
Note that seq[i] where seq is a Float[] is of type Float? ie. the result can be null, if the index is out of the bounds.

Length 8

a else b

As seen above, if a is of type A? ie. can be null, you cannot use it without checking if it is null. It cannot be done with a == null, Ceylon offers various ways to check this. The code above is one of them: if a isn't null, use its value, otherwise, use the value of b (which cannot be null, of course; we can chain the checks...).

Length 9

\{BULLET}

is a valid Ceylon character: you can put any Unicode name between the braces, like \{CARRIAGE RETURN (CR)} or \{WOMAN WITH BUNNY EARS}.

Length 10

if(is T v)

As we seen, we can define union types, meaning that a variable can have one of several types, eg. Integer or Float (or Byte or... etc.).
If all the subtypes derivate from the same interface, we can use the methods of the parent interface.
For example, if we have ArrayList<String> | LinkedList<String> dualList, we can use dualList.size directly.
To use a method specific to one of the member of the union, you have to be sure it is of the given type. For this, Ceylon offers a mechanism allowing in the same shot to check the type, and to downcast it to the specific type: if (is ArrayList dualList) { Integer capacity = dualList.capacity; } is legal because at this point, the compiler is sure to have an ArrayList.
It is equivalent to Java's instanceof and cast in the same shot, just safer: in Java, you can cast to something else than the type you checked!
Note that is is also an operator (resulting in a Boolean) that doesn't narrow down the type. Boolean b = v is T;

Length 11

"N ``p.n``"

Ceylon has string interpolation: you can embed in a literal string an expression between a pair of double backticks. The value of the expression will replace this placeholder. You can have simple local values, field access as shown, complex expressions or function calls. You can have literal strings (with interpolation too!) inside these expressions.

Length 12

f=(A p)=>-p;

Assigns to the f variable an anonymous function defined with the short syntax (fat arrow). Functions are first-class citizens in Ceylon, they are just objects that can be assigned, passed as parameter, returned from another function, etc.
To fit in the length, I omitted the declaration of f which can be done earlier, for example: A(A) f;
Here, f returns the negation of the p parameter which has the type A.
Notice the usage of the negation operator - which must have been overloaded in the definition of A, which then must satisfy the interface Invertible<A>.
Ceylon doesn't support to define arbitrary operators (unlike Scala, where users can get crazy with this feature... :-)), nor even "true" operator overloading, but it supports operator polymorphism: operators are defined (by name, eg. negated for the unary minus) in specific interfaces (here Invertible) that classes needing these operators must implement (must satisfy, in Ceylon vocabulary).

Length 13

C<out T>(T t)

Declaration-site variance: the class C (the class keyword and the class body have been omitted for brevity) declares, in its definition, its type parameter T to be covariant, so C<Car> is a subtype of C<Vehicle> if Car is a subtype of Vehicle.
Collection interfaces (immutable by default), like List or Set are declared covariants.
Mutable collections must satisfy an additional interface with a contravariant declaration (<out T>), defining methods accepting the given class or any supertype of it: a mutable list of Vehicle must accept adding Cars.
Java is using use-site variance, like List<? extends Car>, defined on each List declaration. It is a bit more flexible but puts the burden on the users of the class, so is more cumbersome.
Since version 1.1, Ceylon also support use-site variance for Java interoperability reasons, but promotes declaration-site variance as the preferred method.
Also note the parameter list of the class: it defines both the parameters of the constructor of the class, and the corresponding fields, in the same shot! No need for these cumbersome this.t = t;...

Length 14

for(n in 0..5)

Ceylon doesn't have the classical C-like numerical for loop. Instead, it supports range definitions, and allows to iterate on them.
Here, n (whose type, Integer, is inferred) will go from 0 to 5, included. We could have written 0:6 instead (start, number of items). A range like 5..0 allows count-downs.
These notations are just syntax sugar for declaring instances of the Range<T> class. We can have ranges of numbers, characters or any other type T satisfying the Enumerable interface.

Length 15

return["",0.0];

Return statement in a function. Here, the type of the return value is [ String, Float ]. That's a tuple, of type Tuple.
A tuple is linked list (therefore a Sequence) which captures the static type of each individual element in the list.
We can then access safely each element by its index: Float v = tuple[1];; the compiler knows the size of the tuple and the type of each entry.
Tuples are a practical / compact mean to return several values from a function, where in Java we must create a Pojo (simple, often internal, class with just fields) for this.
Side note: Ceylon doesn't accept abbreviated, unreadable (IMHO) shortcuts for floats: neither 0. nor .0 are accepted, we must write 0.0.

Length 16

shared T v=T(1);

A variable or attribute of a class (field in Java vocabulary) declaration. The variable is immutable (the default) and has a visibility annotation. Unlike Java fields, attributes (and variables) don't have an implicit default value so they must be assigned at the declaration site (or must be, for attributes, in the parameter list of the class).
Note that T(1) creates a new instance of T with one parameter. Unlike Java, we don't need the new keyword.
shared is an annotation, not a keyword. Declarations are private by default, visible only in the code unit where they are declared: the class they belong to, or the package of the file where they are declared, if they are top-level.
shared extends the visibility to the parent: a shared declaration in a class is visible in the class enclosing this class, if any, or otherwise in the whole package containing the class. If a top-level declaration is shared, it is visible to everything that can see the containing package. If the package is shared, it is visible (and its shared declarations) by other packages in the same module, and by code in other modules which import that module. Works like Russian puppets...
We introduced two concepts: packages are like in Java, folders in a folder hierarchy where the path defines a namespace / visibility unit. They allow to organize code in logical groups. Unlike Java, we must declare packages in a special file named package.ceylon in the package they belong to. That's where we declare if a package is shared (or not, by default). On the other hand, we don't have to declare the package on each file of the folder...
Modules are groups of packages, also declared in their own file (module.ceylon) at the root of the package hierarchy. They must declare a version number, and must import the modules (with their version number) used in code belonging to this module. This allows modularity of the code with fine grained management of the required versions.

Length 17

assert(exists x);

Like in Java, assert throws an exception if its expression is false. But unlike Java, the compiler knows that after the assert statement, the condition is true. Here, the expression checks if x, of type T? (remember: that's T | Null ie. either T or Null), exists, ie. is not null. So the compiler accepts to use x.foo after the assert in the same block, because it known it isn't null.
exists can be used in a if too, if that's unsure. assert is used if the programmer knows for sure (except programming error!) that a variable initially null has been set to a non-null value at this point in the code. So assert is used here as a helper of the type checker of the compiler which hasn't flow analysis...

Length 18

class C(Float f){}

Declares a class and its constructor and its attributes in the same shot: the class' parameters are those of the constructor of the class, which then doesn't need to be defined explicitly. These parameters become attributes (equivalent to Java's fields), so no need for this.f = f, the syntax is streamlined, without boilerplate.
Note that a class can have only one constructor, because Ceylon doesn't support method overloading. Instead, it has parameters with default values (and therefore optional parameters), named parameters, etc.
It also implies that the class has an initializer section, containing a mix of declarations, statements and control structures. The initializer is executed every time the class is instantiated and initializes the state of the new instance of the class.

PhiLho

Posted 2015-01-19T12:36:59.320

Reputation: 653

I used (and will use) some of Lucas Werkmeister's suggestions in my entry. – PhiLho – 2015-01-26T18:31:04.643

Semicolons aren't really optional in JavaScript. Either: you include them and your program does what you want, or you omit them and your program does probably something unexpected. In Scala and Lua, there is no time when semicolons are needed (save Scala C-style for loops); you may use them to group statements on to one line for golf. – cat – 2016-05-04T21:14:17.713

@cat Lot of people code JavaScript without semi-colons. They just take care of avoiding these cases where they are necessary. In Scala and Lua, you can find similar cases where semi-colons can be needed. AFAIK, in Scala, you can get out by inserting a blank line where the semi-colon is necessary. – PhiLho – 2016-05-05T22:31:04.150

Those people live dangerously. I also live dangerously, but when I do, I get Segmentation fault (core dumped). :P – cat – 2016-05-05T22:40:18.653

23

Go

Go, also commonly referred to as golang, is a programming language initially developed at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a statically-typed language with syntax loosely derived from that of C, adding garbage collection, type safety, some dynamic-typing capabilities, additional built-in types such as variable-length arrays and key-value maps, and a large standard library.

Link for myself, or anyone who wants to contribute to this answer.

Length 14

var x [9]int32

This is an example of how to create an fixed array. You can access it use normal indexing operation x[8] for example. You can iterate any array or slice using for-range statement, for example:

for index, value := range x { // value == x[index]
}
for index := range x {
}
for _, value := range x {
}

Length 13

var x []int32

This is a longer example of slice, slice is a struct that stores current length, capacity and pointer to an array. to get the capacity you can use cap(x), to get the current length of the slice, you can use len(x) function. To add an element to the last element you can use x = append(x,data) function, if capacity equal to the current length, it will copied to another array, and the slice points to that new array.

Length 12

var x *int32

This is an example of pointer variable, a pointer most useful to change a value that declared outside function, for example:

func SquareIt(n *int32) {
  v := *n
  *n = v * v
}

This function would multiply a variable passed into it (you must prefix with & when passing non-pointer into pointers), for example:

y := int32(12)
SquareIt(&y)
fmt.Println(y) // 144

A pointer also can be used to change function owner's member, for example:

type Person struct {
   Age int
}
func (p Person) Aging1() { p.Age += 1 } // doesn't change the age
func (p *Person) Aging2() { p.Age += 1 } // change the age
func main() {
  me := Person{Age:28}
  me.Aging1() 
  fmt.Println(me.Age) // 28
  me.Aging2() 
  fmt.Println(me.Age) // 29
}

Length 11

interface{}

This is an example of a type that can hold anything. The interface{} translates to "any type that implements at minimum 0 function". Here's better use-case on how to use this keyword

type Stringer interface {
  String() string
}

That snippet above means that Stringer is a type that could hold anything that already implements String() string function (function named String that returns a string), for example:

type Hooman struct {
  Name string
  Age int
}
func (h Hooman) String() string {
  return "I'm a hooman named " + h.Name + " " + strconv.Itoa(h.Age)
}
func main() {
  me := Hooman{}
  me.Name = "kis"
  me.Age = 28
  x := Stringer(me)
  fmt.Println(x.String()) // kis 28
}

Length 10

func X(){}

This is an example of how to create a function. This function named X that holds zero parameter and doesn't return anything. You can add parameters/arguments between the () and return type between the ){, for example:

func Add(a int, b int) int {
  return a + b
}

Or alternative syntax:

func Add(a, b int) (c int) {
  c = a + b
  return
}

A function can have its own owner, this function often called method in another language, to set the ownership of a function, just type the owner between func and the function name, for example

type Person struct {
  Name string
  Age  int
}
func (p Person) Print() {
  fmt.Println("I'm a person named " + p.Name)
}
func main() {
  me := Person{"kis",28}
  me.Print()
}

Length 9

package X

This is an example of the first statement that you must type to create a package/library. The library would be called X, all function, type, constants or variables that declared capitalized, can be accessed from another package by typing X.The_name_of_the_function_or_type_or_constants_or_variables after including the package folder using import keyword. Normally the folder name is equal to the package name, visit here for more information about code organization.

Length 8

[]int{3}

This is an example on how to create a slice that points to an array that contains an element with value 3. To increase the slice you may want to use append function, for example: x := []int{3}; x = append(x,7), now that slice will point to an array that have a value of 3 and 7, that equals to []int{3,7}, to get the length of that slice, use len function, to get the capacity of underlying array, use cap function.

Length 7

strconv

This is the name of standard library that useful to convert mostly anything from/to a string, for example:

package main
import `strconv`
import `fmt`
func main() {
  fmt.Println(strconv.Itoa(1234) + ` is a string now`)
}

Length 6

struct

Struct is a keyword to create a record or a new data structure, that compose another type, this is an example of how to create a new type called Person

type Person struct {
  Name string
  Age  int
}

Length 5

[]int

This is an example of slice data type, slice is a struct that have pointer to real array, a current length of the slice and capacity of that array. Slice is just like a microscope that shows only a part or whole of original array.

Length 4

x:=3

This is an example for a shortcut to create a variable named x and initialize it with int value of 3. The longer version to do the same thing is: var x int = 3. There's no need to add semicolon at the end of each statement.

Length 3

1.2

This is an example on how to create a float constant with float32 or float64 depends on the context.

Length 2

``

Backquote is the string literal, inside those quote could be almost anything (including newline) except the backquote itself.

Length 1

1

This is the example of number literal, this number could be anything, rune (character), uint8 or byte, int8, uint16, int16, uint32, int32, uint, int, uint64 int64, float32, float64 depends on the context, the default is int.

Factoid

Gopher (the mascot of go programming language) is a real animal (rodents family).

Kokizzu

Posted 2015-01-19T12:36:59.320

Reputation: 1 531

23

아희(Aheui)

아희(Aheui) is the first esoteric programming language which uses Hangul, the Korean alphabet. The word '아희' means '아이' in Old Korean, which means 'child'.

Aheui works similar to Befunge. It has 26 stacks and one queue.


Factoid

There is a Twitter bot which runs Aheui code for you.

You can try programs below at here.


Length 1

This is most simple program in Aheui. It does nothing and terminates.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
ㅎ
    ㅎ                  Terminates program

Length 2

아희

Yes, the name itself is also a valid, harmless program.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
아
    ㅇ                       Initial ㅇ does nothing
             ㅏ                Move cursor by one character right
----------------------------------------
희
    ㅎ                       Terminates program
             ㅢ                (not executed)

Length 3

밯망희

This is simple character code converter. Surprisingly, it is shorter than same C or Python program.

Side note: '밯망희' is pronounced similar to the word '방망이', which means 'bat'.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
밯
    ㅂ                       Push to current stack (defaults to (none) stack)
                      ㅎ       from input as character (it will be saved as integer)
             ㅏ              Move cursor by one character right
----------------------------------------
망
    ㅁ                       Pop from current stack
                      ㅇ       to output as integer (it will be saved as integer)
             ㅏ              Move cursor by one character right
----------------------------------------
희
    ㅎ                       Terminates program
             ㅢ                (not executed)

Length 4

박빠나망

One sad point about Aheui is there is no shorter expression for the integer 1. So we need two numbers and calculate with them. Since this program has no termination command, it will print 1 infinitely.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
박
    ㅂ                       Push to current stack (defaults to (none) stack)
                      ㄱ       the integer 2
             ㅏ              Move cursor by one character right
----------------------------------------
빠
    ㅃ                       Duplicate top number of current stack
             ㅏ              Move cursor by one character right
----------------------------------------
나
    ㄴ                       Pop two numbers from current stack
                               divide second number to first number
                               push result to current stack
             ㅏ              Move cursor by one character right
----------------------------------------
망
    ㅁ                       Pop from current stack
                      ㅇ       to output as integer
             ㅏ              Move cursor by one character right
                               (If cursor reaches the end of code space, it wraps)
                               (So in this case, cursor will go to 박 again)

Length 5

바뱍멍다뼈

It simply prints even numbers infinitely. It also shows how to loop Aheui programs without wrapping.

Explanation

    Initial  Medial   Final  Explanation
----------------------------------------
바
    ㅂ                       Push to current stack (defaults to (none) stack)
                               if there is no final consonant, it pushes integer 0
             ㅏ              Move cursor by one character right
----------------------------------------
뱍
    ㅂ                       Push to current stack (defaults to (none) stack)
                      ㄱ       the integer 2
             ㅑ              Move cursor by two characters right
                               (In this case, cursor will go to 다)
----------------------------------------
멍
    ㅁ                       Pop from current stack
                      ㅇ       to output as integer
             ㅓ              Move cursor by one character left
----------------------------------------
다
    ㄷ                       Pop two numbers from current stack
                               add two numbers
                               push result to current stack
             ㅏ              Move cursor by one character right
----------------------------------------
뼈
    ㅃ                       Duplicate top number of current stack
             ㅕ              Move cursor by twoe character left
                               (In this case, cursor will go to 멍)

If we make this program into infinite one way program, it will be:

바박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망박다빠망...

Snack

Posted 2015-01-19T12:36:59.320

Reputation: 2 142

23

PostScript

Factoid

PostScript is a language designed for printer rasterization engines. It is nonetheless a mostly feature complete programming language based on stack manipulation. This makes it relatively easy to extend the drawing primitives.

PostScript can be executed by many devices, and programs. Aside GhostScript, if you include a encapsulation header, you can use programs such as Word, Illustrator, Indesign as preview (possibly live if you link the file) for your code. This means that surprisingly many users even on the Windows platform can execute your program with no extra installation.

One char snippet

2

Puts the number 2 topmost on your execution stack. Nothing fancy done with this yet, but hey, we have allocated some memory.

Two char snippet

==

Print and remove topmost item in stack to stdout. Since not all systems are guaranteed to have a meaningful stdout this may in fact do nothing. Raises an error if stack is empty.

Three char snippet

(a)

Push a string containing a to the stack.

Four char snippet

save

Save the state of your virtual machine and put a save object on top of your stack. You can then use restore on this object to return to the global saved state at any time.

Five char snippet

5 sin

Calculate the sine of 5 degrees. Postscript quite universally thinks of angles as degrees, as opposed to more mathematical radians of many languages use.

Six char snippet

moveto

When executing drawing instructions, PostScript acts like a plotter (or pen in hand). The moveto command moves the virtual pen to a location specified by the two topmost items on the stack; topmost being the y direction and the second the x direction.

Seven char snippet

1 2 add

And finally we have enough chars to actually compute something trivial. Here we push 1 and 2 to the stack. Calling add then pops them both, adds them together, and pushes the sum onto the stack. Leaving 3 on top of the stack.

Eight char snippet

/v 9 def

Define symbol v as 9. This is mostly equivalent to doing v = 9 in most other languages. So now the previous example could look as v 2 add and it would result in 11 in the stack.

Ten char snippet

0 2 8{}for

A for-loop. Normally you'd add spaces around the function {} but I'm running out of chars. This produces numbers even numbers 0 through 8, as the stepping is 2. So the stack after this would be 0 2 4 6 8. 20 more chars and we can start drawing stuff. (not a good language for golfing)

Eleven char snippet

/a {add}def

Simple function definition; the function goes between the curly brackets and acts upon the stack. Note how it uses same mechanism as snippet 8. Now you could write the 7 char snippet as 1 2 a.

Twelve char snippet

4 3 gt{1} if

So here you go some flow control, if 4 is greater than (gt) 3 execute function {} which in this case deposits 1 in the stack.

Thirteen char snippet

0 0 6 0 5 arc

Make a 5 degree arc with a radius of 6 at the origin (0, 0). Note this does not actually draw anything yet; it prepares for drawing by constructing something that's called a 'user path'.

Fourteen char snippet

20 0 translate

Changes the transformation matrix so that your drawings are henceforth positioned 20 units more right. This is useful if you want to repeat the same drawing routine in different places. PostScript coordinates are measured from the bottom left corner of your drawing surface and each unit is one PostScript Point (a unit Adobe invented) that is 1/72 of an inch.

Eighteen char snippet

1 1 5 5 rectstroke

Draws a stroked rectangle onto the canvas in the lower left corner of your page.

Twenty-one char snippet

4 4 moveto 2 5 lineto

Puts a line segment into the drawing buffer.

joojaa

Posted 2015-01-19T12:36:59.320

Reputation: 363

@mbomb007 Edit appreciated – joojaa – 2015-06-24T08:23:40.757

Need one more number for x y radius ang0 ang1 arc -. I only noticed this because I've implemented arc.

– luser droog – 2016-01-14T06:03:21.997

When you get to 19, you can 0 0 1 1 rectstroke. – luser droog – 2016-01-14T06:39:08.093

@luserdroog right you are will fix as soon as i have a computer in front of me. – joojaa – 2016-01-14T09:22:06.467

23

Plurp

Factoid: Plurp is a two-dimensional programming language closely related to
><> (fish) and Befunge. It is inspired by ><>.

1 character

>

An infinite loop. Like in ><> and Befunge, code will wrap around in Plurp.

In fact, any command but ; when by itself in a program would result in an infinite loop.

2 characters

1i

Outputs 1 indefinitely. Any number from 0 to 9 would do pretty much the same.

3 characters

)s;

Finally! Something interesting! This is a cat program which outputs its input.

4 characters

1~i;

Demonstrates the pop (~) function. Although this pushes 1 to the stack, it is popped and therefore the program outputs nothing.

5 characters

'a's;

Prints a. This demonstrates the string parsing function: when an ' is encountered, the rest of the characters are pushed to the stack as character codes until another ' is encountered. This leads to the escape for ' being quite costly: '39&'

The & used in '39&' concatenates the top two numbers on the stack (39 is [3, 9] but 39& is [39]).

6 characters

123|i;

Demonstrates the right-shift function. 1, 2, and 3 are pushed onto the stack, then the stack is shifted right (by one position). The output of this program is "312", as the 3 wraps around.

| can also be replaced with \ (the left-shift operator) to shift the stack one position left instead of right. This has a surprising number of applications in Plurp.

7 characters

8[42i];

Like ><>, Plurp can create multiple stacks and run operations on each stack independent of the others.

There are three different kinds of stacks - additive [, overlap (, and copy additive {. Stacks are classified by their behaviours when opened and closed with ] or flattened with f.

Additive stacks will be empty when open ([]) and will add their data to the end of the next stack when closed. 4[2]i; outputs 42.

Overlap stacks will be empty when open and will add their data to the beginning of the next stack when closed. 4(2]i; outputs 2.

Copy additive stacks are like additive stacks, but they open with the data of the last stack already in them. 4{2+]i; outputs 442.

8 characters

42&"i"i;

Like ><>, Plurp has a register (albeit only a single one). When a " is encountered, the interpreter checks if the register is empty. If it is, the top value on the stack is popped and pushed into the register. Otherwise, the value in the register is popped and pushed into the stack.

Therefore, even though there are two i commands, only one outputs 42 because the other is called while 42 is in the register and not the stack.

9 characters

39&'|||s;

A quine! From all the above snippets, you have enough information to figure out how this works. The key is that string parsing wraps around in this programming language, much like all regular commands.

Read Me

Currently the interpreter is broken due to the addition of an infinite-loop prevention system in Khan Academy. I'm working to fix it, and once I do I will catch up with this answer!

BobTheAwesome

Posted 2015-01-19T12:36:59.320

Reputation: 509

Why is this so popular!? – BobTheAwesome – 2015-07-01T13:53:23.873

1Are you thinking of names yet? – mbomb007 – 2015-09-04T22:03:18.100

No, I really need to add more programs though. – BobTheAwesome – 2015-10-16T02:13:10.270

le bump please add programs* – Conor O'Brien – 2016-07-26T00:48:09.197

Hi! I've finally gotten around to re-making a working interpreter. I will be adding programs soon! – BobTheAwesome – 2017-02-05T16:12:45.443

23

QBasic

The programming language that everybody grew up on[citation needed]--at least, everyone who grew up with MS-DOS during the 90s.

Factoid

QBasic is actually an interpreter and an IDE together. When you enter code, the QBasic editor automatically formats it for things like whitespace and capitalization. The QB64 emulator, which I'm using to test my programs, gives the option of turning auto-formatting off, allowing a few nice golfing shortcuts in an otherwise fairly verbose language.

Length 1

1

This is a valid QBasic program--but only because QBasic allows line numbers. The above is therefore an empty statement (on line number 1), which does nothing.

Length 2

?a

Lots of stuff going on here:

  • ? is a shortcut for PRINT.
  • a is a variable. Since it doesn't have a type suffix and hasn't been declared with DIM, it is numeric; so it is auto-initialized to 0.
  • Thus, this program is basically equivalent to PRINT 0. But because QBasic is optimized (?) for outputting numeric data in tables, what it actually prints is 0 . (The leading space is so 1 and -1 will line up properly, and I suspect the trailing space is so that printing multiple numbers in a row won't result in something like -1-2-3.)

Length 3

CLS

QBasic doesn't use an output stream like C-based languages; instead, it uses a cursor to write stuff to a window (see snippet 13 for more on that). The DOS implementation doesn't clear the window between runs, so it can start to get cluttered after a while:

 0 
 0 
 0 

--which is why most QBasic programs have the CLear Screen command somewhere near the beginning.

(The QB64 emulator starts over with a blank screen each time you run your program, which I find just a little disappointing.)

Length 4

BEEP

Does just what you think it does.

What I like about QBasic is that it has fun commands like this built into the syntax, whereas other languages usually require external libraries or weird workarounds. In Python, for example, the quickest way to get a beep is the extremely cryptic print("\a"); but that doesn't even work in all environments (in particular, the IDLE shell that comes with Python prints a bullet character instead).

Length 5

?2^42

^ is exponentiation, of course. (Don't know what possessed C and its derivatives to use it for bitwise xor.)

Despite the fact that this looks like integer math, we don't get an overflow. The default numeric type in QBasic is actually SINGLE, which is a floating-point number that shows (up to) seven significant digits. If the fractional part is zero, it will display as an integer: for example, PRINT 1.0 outputs 1. The result above has more than seven significant digits, however; so we get it in scientific notation as 4.398047E+12.

Annotating one of the operands with the # suffix would coerce the expression to DOUBLE precision, giving up to fifteen significant digits: ?2#^42 gives 4398046511104.

Length 6

?1:RUN

Our first multi-statement program! : is a statement separator.

The RUN command can be used in a few different ways. If you give it the name of another QBasic source file, it will switch execution to that program. If you give it a line number in the current program, it will restart the program at that line. (This is different from a GOTO because all variables are cleared, as if starting the program from scratch.) And if you don't specify an argument, it will restart the program from the top. The code above prints 1 infinitely.

If you don't want the 1s on their own lines, you could use ?1;:RUN--the semicolon suppresses the newline when printing. But that will actually give you 1 1 1 ... (see the length-2 snippet for why). To fill the screen with 1s, you'd need to use a string: ?"1";:RUN.

Length 7

INPUT x

The INPUT statement by default displays a ? prompt and waits for the user to enter a value. Lacking a type suffix, x is a single-precision numeric variable, so anything like 3.14 or -42 is valid input. What happens if you try to enter something that's not a number?

? Jabberwocky
Redo from start
? 

It's a bit cryptic, and it can royally mess up the alignment if your program is using some kind of text-based user interface, but at least the program doesn't crash, interpret the input as 0, or anything weird like that. ;^)

Note: QB64 doesn't even let you type invalid characters when an INPUT statement asks for a number.

Length 8

PLAY"CF"

Music is yet another feature awesomely built in to QBasic. This code plays two quarter notes (middle C and middle F). A PLAY string has ways of changing the octave, playing sharps and flats, changing the duration of notes, and so much more!

Length 9

SCREEN 12

Different SCREEN modes in QBasic allow for different graphical capabilities: various resolutions, color vs. black-and-white, text-only or graphics-capable. Historically, these were included to account for differences among display hardware. The default mode, SCREEN 0, is text-only, so any program with graphics in it has to start with a SCREEN statement. (Pretty pictures later if I get more votes!)

Length 10

?4*ATN(1#)

Would you care for some pi? QBasic has a good number of math functions built in, ArcTaNgent among them. The # type annotation is used here to make the resulting value DOUBLE, so we get more digits: 3.141592653589793.

Length 11

COLOR 2:?42

Time to get colorful.

Green 42 (Shown 2x actual size)

In the default SCREEN 0, QBasic offers 16 foreground colors:

The 16 colors in QBasic

Each color 8-15 is a lighter version of the corresponding 0-7 color. The darker colors 0-7 are also available as background colors, and adding 16 to a foreground color makes it blink! (See this thread, particularly the bottom post, for a great historical explanation.) So, since a COLOR statement affects everything subsequently printed, we can write this:

COLOR 25,4

and see this:

Blinking "Press any key"

Trippy.

Length 12

DRAW"F3U7R9"

The DRAW command takes a string of codes and draws stuff on the screen. As a graphics command, it cannot be used in the default screen mode, so you'll need to combine this snippet with snippet 9 in order to run it. This example goes 3 pixels diagonally down and right, 7 pixels up, and 9 pixels right, for a tiny square root symbol:

QBasic DRAW command--square root symbol (Shown 2x actual size)

Length 13

LOCATE 7,8:?9

Recall (from snippet 3) that QBasic outputs text to a window, not an output stream. The LOCATE command allows you to set the cursor location for output. So if you want to display something halfway down the screen, you don't need to print a bunch of newlines first--just LOCATE to the right row and column.

Using LOCATE command

Importantly, this doesn't affect any other text on the screen (except when directly overwriting it), which makes QBasic very straightforward for creating textual user interfaces--or dungeon games. Most languages would have to use control codes or a library like curses.

Length 14

GOTO a
?1
a:?2

What would QBasic be without GOTO? The much-maligned feature is alive and well here, allowing arbitrary jumps in program flow to defined labels. The above snippet, of course, skips to the third line and outputs 2.

A label must come at the beginning of a line. It can be any identifier followed by a colon; or, it can be a BASIC-style line number, sans colon.

While it is true that 1) most uses of GOTO can be replaced by conditionals or looping constructs and 2) those that are too complicated for this treatment are probably a bad idea to begin with, I still like GOTO, for a couple of reasons. First, it's how assembly works under the hood, so learning it first in QBasic is valuable practice. Second, I still think it's more readable (and less redundant) to write code like this:

getNumber:
INPUT x
IF x = 0 THEN PRINT "Enter a nonzero number": GOTO getNumber
PRINT "The inverse is"; 1/x

than the Python equivalent:

x = float(input())
while x == 0:
    print("Enter a nonzero number")
    x = float(input())
print("The inverse is", 1/x)

Length 15

RANDOMIZE TIMER

QBasic does (pseudo)random numbers via the RND function, which is normally invoked without arguments and returns a random number in the range [0, 1). However, you'll get the same sequence on each run of the program unless you seed the PRNG with the RANDOMIZE statement. The usual seed is TIMER, which returns the number of seconds since midnight. This provides a different seed on each run of the program... at least, if you don't run it at exactly the same time each day.

If you do want the same numbers each run (maybe for testing purposes), you can pass a constant to RANDOMIZE--or just put RANDOMIZE without specifying a seed, in which case you'll be prompted when you run your program:

Random-number seed (-32768 to 32767)? 

Nobody can say QBasic isn't user-friendly.

Length 16

CIRCLE(9,9),8,,2

Graphics command: combine with snippet 9 to run.

QBasic's drawing commands are interesting because they each have a unique syntax, tailored to make the most sense for the particular command. The syntax for CIRCLE is CIRCLE (x, y), radius[, options]. (If you think that's odd, just wait till we get to see LINE in snippet 18.)

The first option to CIRCLE is color: we could have drawn a green circle with CIRCLE(9,9),8,2. But we've got an extra character to play with, so let's leave the color option blank (defaulting to white) and look at the next option. This happens to be startRadian. A value of 2 means that instead of a full circle, we get an arc of 2π - 2 radians:

Arc of circle (Shown 2x actual size)

(Note that this apparently follows the standard quadrants system, despite the fact that QBasic has the origin at the top left with the positive y-axis pointing down.) The remaining CIRCLE options are endRadian and aspect, which allows you to draw ellipses:

CIRCLE(51,26),50,,,,0.5

Half-squashed circle

Length 17

LINE INPUT s$:?s$

Reads an arbitrary line of text from the user and echoes it back.

What's important here is the word "arbitrary." The reason for the existence of LINE INPUT is that the regular INPUT command can't read commas. It treats them as field separators, so you can get two strings in one go by doing INPUT a$, b$. (Also useful for reading comma-separated data from a file.) But what if your input contains commas? Well, you can wrap it in double quotes and it'll treat the comma as part of the string. But what if your input also contains double quotes? That's when you need LINE INPUT, which simply reads everything until you hit enter.

Length 18

LINE(1,1)-(9,9),,B

Graphics command: combine with snippet 9 to run. Draws a line from (1,1) to (9,9), right? Well... not exactly.

It's a box! (Shown 2x actual size)

This would create a diagonal line, except that we've also specified the B option for "box." So instead of a line, we get a rectangle. There's also BF for "box, filled." (As in snippet 16, the empty space between commas is for the unused color argument.)

I'm actually a fan of this unusual syntax, whenever it makes sense for the given command. I find that it's a mnemonic aid. Contrast the above with a function that takes a gajillion* positional arguments--you can never remember which one is which--or half a gajillion keyword arguments--you 1) have to remember the names of the keywords and 2) can end up with a pretty long line of code if you use multiple arguments. (I know the counterarguments; I'm just saying that this is something I enjoy about QBasic.)

* Slight hyperbole.

Length 19

?0:PAINT(10,4),9,15

Graphics command: combine with snippet 9 to run.

PAINT takes a starting point, a fill color, and a border color. It does a flood fill until it hits border-colored pixels or the edge of the screen. It's typically used to fill circles, rectangles, and other graphics figures. But hey, printed text is just pixels on the screen too:

0 donut filled with blue(berry) jelly (Shown 2x actual size)

Length 20

?ASC(INPUT$(1));
RUN

INPUT and LINE INPUT aren't the only ways to get input in QBasic. The INPUT$(n) function reads n keypresses and returns them as a string. (It can also be used to read from a file or a serial port.) INPUT$ does not display a prompt or echo the characters to the screen as they are typed. It therefore has a myriad of uses, from password entry to the famous "Press any key to continue."

The above program waits until the user presses a key, prints the ASCII code of that character, and loops infinitely using RUN (see snippet 6). Entering ABC123<esc><cr><tab><bksp> will result in output of

 65  66  67  49  50  51  27  13  9  8 

DLosc

Posted 2015-01-19T12:36:59.320

Reputation: 21 213

1I know this is old, but I gave you the 13th upvote, and I'm interested in seeing what you can do with 13 characters (you mentioned it in your length 3 snippet). I grew up on QB45 and absolutely loved it. – vastlysuperiorman – 2016-03-31T19:28:33.107

23

MarioLANG

MarioLANG is a two-dimensional programming language based on Super Mario. The source code's layout is similar to a Super Mario world, however the programs written in MarioLANG when compiled looks completely like a normal application, it is even turing complete!

Length 3 Snippet

!
=

Mario (our parser) starts in the upper-left corner, then drops down until he hits a = (or floor), then he executes whatever instruction is on top of that floor. Here it's the ! command, which tells Mario to stop walking.

Length 5 Snippet

+!
==

This time, Mario encounters a + sign, which tells him to increase the cell under the pointer by one. Once again, he encounters a ! sign that tells him to stop.

Length 6 Snippet

++:
==

What good is a language that can't output? Here, Mario encounters 2 +s (causing the cell to have a value of 2), then a : which outputs the numeric value of the cell under the pointer. This program will output 2. Also, note there is no floor: Mario falls until EOF where he stops.

Length 7 Snippet

+):
===

This should output 1 - right? No, it outputs 0. That's because the ) command moves the pointer right one cell, like >in Brainf**k. ( does the same thing, but to the left instead.

Length 9 Snippet

 >!
>^=
==

Mario can also jump! When he encounters the ^ jump command, Mario will move up one space. There is also the > command to make him go right onto the next platform.

Length 11 Snippet

[@+:@
=====

Two new commands are introduced: [ and @. [ tells Mario to skip the next instruction if the cell pointer is 0. @ tells Mario to walk the other way. Here, Mario sees the [, and since the cell is 0, he skips the @. Then he adds one to the cell (+), outputs the number (:), and walks the other way (@). This is an infinite loop.

Length 13 Snippet

++
==
:+<
 ==

Mario can also walk in different directions: the < command tells Mario to walk left. The 3 +s add 3 to the cell, and the : outputs 3. Once again, Mario falls until EOF.

Length 15 Snippet

! 
#

>++:
"===

Going down, Mario?

The # and " commands are elevators: # is the start, where Mario gets on if he is not moving, and " is the bottom, where he gets off, we need to tell mario where to go once he come out of the pipe, so we use >. He then hits two + and a :, outputting 2. I've used a down elevator, but an up one would also work.

Length 17 Snippet

;
 -<
 ="
>[!
==#

Mariolang Can also use input. Here we use ; to read the imput as an integer, then we decrement our value until it reach 0, at that point we exit the loop and the program stop

ASCIIThenANSI

Posted 2015-01-19T12:36:59.320

Reputation: 1 935

Update already! This sounds pretty cool. :) – Florrie – 2015-10-13T12:22:28.170

@towerofnix Had to go inactive for a while, didn't realize how popular this became. I've added 5 new snippets. – ASCIIThenANSI – 2015-10-26T21:30:50.837

23

Labyrinth

Labyrinth is my new two-dimensional programming language. I'm unreasonably proud of how it turned out, so I figured this would be a good place to introduce it and maybe popularise it a bit.

Factoid

Labyrinth is a 2D stack-based language without any control flow commands. Instead, control flow is determined by the layout of the source code, which is supposed to resemble a maze (hence the name).

Length 1 snippet

'

Every command in Labyrinth is a single character and occupies a "cell" in the 2D source code. Let's start with the latest addition to the language, because it's useful during programming and because it let's me get some basics out of the way.

The command ' is normally just a no-op, but when the interpreter is invoked with -d (debug mode), ' prints debug information about the current state. This information includes the grid (i.e. the source code; we'll see later why this is useful), the position of the IP, the moving direction of the IP, as well as the stacks. This is all the state there is in Labyrinth.

What stacks? Labyrinth operates on two stacks, "main" and "auxiliary". They both initially hold an infinite amount of zeroes, and can hold arbitrary signed integers. I picture them with the tops facing each other, growing towards the centre, i.e.:

Main [ ... 0 0 1 3  |  -123 345 1 0 0 ... ] Auxiliary

where ... represents the infinite amount of zeroes at the bottom. This is also how they are printed by ' and how some operator symbols have been chosen.

One last detail: Labyrinth doesn't terminate unless the IP hits a specific command. In a 1-cell program, the IP will instead repeatedly execute that one cell. This means the above program is simply an infinite loop that never prints anything. If we switch on debug mode, the code will instead repeatedly print

Grid:
'
Position: (0,0)
Direction: East
Main [   |   ] Auxiliary

Note that both stacks are currently empty (the infinite amount zeroes is, of course, not printed but implied).

Length 2 snippet

[]

What's this? I don't know yet. [ and ] are the only two non-letter characters which don't have an assigned function yet (and letters won't get any). So currently these are "walls" just like spaces and letters. A program which consists only of walls is considered empty and terminates immediately.

But: I am planning to add commands for these two characters eventually, and this snippet serves as a placeholder until then. I'm happy to receive suggestions what these two characters should do! If you have an idea let me know in The Nineteenth Byte or the dedicated Labyrinth chat room.

Length 3 snippet

Okay, real code now...

90.

Let's take a nap... this code prints an infinite stream of ZZZZZZZ.... There are two things of note here:

First, in languages where each character is a separate command you can often only push numbers in the range 0..9 and have to build larger numbers with arithmetic. This can get annoying, so in Labyrinth instead, a digit will multiply the top of the stack by 10 and then add itself. This lets you write out numbers in decimal in the code. Emmental has this feature as well. So 90 will actually create a 90 on the stack for . to print as the character Z.

Second, as opposed to many other 2D languages, the edges of Labyrinth's source code don't wrap around. So the IP hits a dead end after executing .. When this happens, the IP simply turns around and continues in the opposite direction. So the IP keeps bouncing back and forth in the source code, executing

90.090.090.090.090...

and so on, repeatedly printing Z.

Length 4 snippet

4!\@

Printing is important, so Labyrinth comes with two more commands in addition to .. ! prints the integer value in decimal (as opposed to treating it as a character code). Note that it doesn't print a newline. But printing newlines is quite a common task, and having to do _10. each time is annoying, so there's \ which just prints a single newline.

I'm also introducing @ here. This terminates the program, so we don't have to keep writing infinitely-looping code. So this snippet happens to print its length 4, a newline and then exits cleanly.

Length 5 snippet

I think we can spare a newline now:

?
~!@

? is the input-equivalent of !: it reads as many bytes from STDIN as it can to form a valid (signed) integer and pushes it onto the main stack.

Now the IP can't move to the right, because there's a wall there (spaces and letters except v are walls; the source code is implicitly padded to a rectangular area with spaces). However, the IP can move down so that's what it does. This is essentially the dead-end rule from snippet 3: if there is only one non-wall neighbour, move there. (From now on "neighbour" will always imply "non-wall neighbour").

~ computes the binary NOT of the top of the stack. The IP hits another wall. However, this time it's not a dead end. It doesn't have to turn around, but it can take a left turn, so that's what it does instead. ! prints the newly computed value, @ ends the program.

This turning behaviour is important, so here are the exact rules for when the current cell has exactly two neighbours:

  • If the IP can keep moving straight ahead, it does.
  • Otherwise, the IP moves such that it doesn't reverse direction.

These two rules allow the IP to follow any "corridors" of code, even around bends. There is one more subtle special case for two neighbours, but we'll get to that later.

Length 6 snippet

,)@
.(

Our first real program. Those 6 bytes implement cat. , is to ? what . is to !: it reads a single byte from STDIN and pushes its value onto the stack. When we hit EOF, it pushes -1 instead. I have borrowed ( and ) from CJam: they decrement and increment the top of the stack respectively.

But the most important thing about this snippet is what happens after the read byte has been incremented by ). This time, the current cell has three neighbours: the one we came from, one straight ahead (the @) and one which requires a right-turn (the (). So where do we go?

For these kinds of junctions (3 or 4 neighbours), the top of the main stack is examined (but not popped). If it's zero, the IP continues moving straight ahead. If the top value is negative, it takes a left-turn. If it's positive, it takes a right-turn. In the case of 3 neighbours, any of those decisions might hit a wall: in that case the opposite direction is picked. This little mechanic is the way to implement control flow in Labyrinth.

And what happens in this specific case? As long as we're reading bytes (which will be 0 or greater), the ) increments the value to a positive number so we take a right turn. ( decrements it back to its original value before it's printed with . and we move on to reading the next byte. At EOF, the ) will increment the -1 to 0, so the IP moves straight ahead, leaves the loop, hits the @ and terminates the program. Nifty, isn't it? :)

Length 7 snippet

<.$,23>

We've seen in 3 how we can write simple endless loops, but the problem is the IP bounces back and forth. Not every code can easily be written such that it will still do the right thing if ran as a palindrome. Can we write similarly simple (i.e. linear) loops which just run each command once per iteration, but still put them on a single line?

For that, let me give you a glimpse at Labyrinth's second major feature (the first being how control flow works). It has four commands <, >, ^, v which can modify the source code at runtime. Each of them pops one value from the main stack and then rotates (i.e. shifts cyclically) a particular row or column of the grid by a single cell. If the IP is on the row or column that is being shifted, it moves with the shift, potentially through the edges of the grid. This shift does not affect the IP's current orientation, and the IP will still make its normal move afterwards. I'm not aware of any other language where source code manipulation works like this.

So let's look at this code again. We start on <, which pops a 0 from main. The 0 indicates that the IP's own row is being shifted (to the left). So we get this code:

.$,23><

But the IP is now at the right end of the grid. It can only move left so it does. Next it hits >, which shifts the source code back in place:

<.$,23>

The IP is still at the right end, moving left. Now it executes the actual content of the loop, 32,$.: push a 32, read a byte, bitwise XOR, write the byte.

What does this do? If the program receives a stream of letters on STDIN, it will change the case of each letter and print them to STDOUT. E.g. abCdE turns into ABcDe. If we reach EOF on STDIN the program will terminate with an error, but let's not worry about that.

I will try to show some more elaborate use of the grid rotation commands in later snippets.

Length 8 snippet

"
:-"
~"

You should actually consider this one a snippet, not a full program. Assume that the IP enters this from the top and will leave to the right. Let's see what it does:

As mentioned in the first snippet, " is a no-op. It can be used to lay out paths of the Labyrinth without affecting the stacks.

: duplicates the top of the main stack. If that value is non-zero, the IP will take a left-turn towards the -, which subtracts the two values. Since they are both the same, this gives zero and the IP leaves the snippet to the right.

If the duplicated value is zero instead, the IP moves further down. ~ takes the bitwise NOT, turning 0 into -1. The IP then follows the bend through the no-op, onto the -. Now this computes 0 - (-1), i.e. 1. The top of the stack is now positive and the IP takes a right-turn and leaves the snippet in the same direction as before.

In summary, this turns non-zero values into 0, and zeroes into 1. It is therefore a very compact implementation of logical NOT.

Length 9 snippet

 "
"_;
 ;

Again, consider this a snippet. The IP enters it from either the left or the top.

A well-known problem in 2D languages is the wire-crossing problem. While Labyrinth doesn't need wire-crossing (or source manipulation) to be Turing complete, being able to cross paths of the Labyrinth can be very helpful when laying out the code.

There are several ways to cross "wires" in Labyrinth, and this snippet is the simplest one. _ pushes a zero onto the main stack (this command is also necessary to push new numbers on the stack, because all the digits, including 0 just change the value of the to of the stack). So no matter whether the IP enters from the left or the top, the main stack will hold a 0 when the IP reaches the intersection. This means the IP will travel straight ahead. ; discards the top of the main stack, in order to return to the previous state.

Length 10 snippet

_v"
 "
 )"

Consider this a snippet, but be aware that the height of the full source code should not be greater than three lines. The snippet is entered at the top left (on the _, going east) and exited either at the top right or bottom right (going east). The snippet also assumes that there's a 0 on top of the main stack.

I mentioned in snippet 5 that there's one more case to be considered for control flow when the current cell has two neighbours. Let's see what happens here:

The _ pushes another zero onto the stack. Now the stack rotation v pops that zero and shifts the current column down by one, taking the IP with it:

_)"
 v
 ""

Now the IP is still facing east, and the current cell has two neighbours, above and below. This means the IP can neither move straight ahead, nor could it reverse its direction, so in principle both choices are valid. If the top of the main stack was non-zero, we'd apply the same rules as for three or four neighbours: for a negative value turn left (north), for a positive value turn right (south). But the top of the main stack is zero. In this particular case, the direction is chosen randomly (choosing uniformly between the two options). This is Labyrinth's built-in PRNG. It's quite tricky to use, because the required conditions on the IP can only be set up with the grid rotation commands, and it only makes a binary decision, but it can be used to build up larger random numbers with some effort.

Now that the IP has chosen a random direction, what happens next? If it goes up, the zero on the stack is incremented to 1 and the IP takes a right turn and leaves the snippet at the top. If the IP went down instead, the zero remains unchanged and the IP leaves the snippet at the bottom. So this snippet can be used to either a) just generate a random bit on the stack or b) choose one of two execution paths at random (or both).

Martin Ender

Posted 2015-01-19T12:36:59.320

Reputation: 184 808

1The use of digits as operators that also work for creating multi-digit numbers is incredibly smart! I'll keep that in mind when designing future esolangs. +1 'cause I'd like to see more. :) – ETHproductions – 2015-09-05T19:33:54.813

I'm gonna have to learn this language, it looks like it'd be fun to golf in. +1 because I'd like to see what it can really do. – ASCIIThenANSI – 2015-09-22T19:08:49.720

I have some ideas for [ and ]. They could be used for bit-shifting. They could be used for some sort of crazy goto (maybe one pops twice and goes to those coordinates on the grid, and maybe the other goes to 0,0 always). You could change all of the arithmetic to be floating point and [,] could be floor and ceiling. Just some ideas. I love the language, btw! – Robert Hickman – 2016-11-07T15:51:21.793

23

AppleScript (or osascript, from command line)

Factoid

Applescript is a programming language most commonly used for automating events in the system environment and Aqua interface interactions in Mac OS X, though it can be used as a normal programming language as well. Its syntax boasts an (almost) English grammar method of writing, making it easy-to-use for programmers, beginners or otherwise.

Length 1 Snippet

1

Okay, it looks a little boring.

Basically, this is a very short operation. I take 1 and do nothing with it. Since AppleScript always returns the result of the final operation, it will print "1" to the console.

1

Length 2 Snippet

it

This keyword defines the current object being told to do something: if I was telling Finder to do something, it would return Finder. However, since I haven't defined anything for it to be tied to this is equivalent to

me

Which defines the top-level script object. So, at the end of the day, both of these 2-byte codes will return

«script»

Which is how AppleScript defines itself.

it

Length 3 Snippet

We're slowly creeping our way to show the full functionality of AppleScript...

{1}

This is the general array syntax in AppleScript. Arrays in AppleScript act more like ArrayLists in that they are not restricted as to what they may hold, and you can concatenate onto them at any time with &. (note that & is also the string concatenation symbol and in some cases may cause conflicts).

array

Length 4 Snippet

tell

While this code by itself won't function due to the enormous verbosity AppleScript, this is the keyword that allows the "telling" of commands to an application. This unlocks enormous potential, from the automation of GUI interactions to changing System Settings with a click of a button.

Length 5 Snippet

log""

This is another benefit of AppleScript: auto-complete. AppleScript is very good at golfing (not really) due to its ability to correct code. This code will not be executed. Oh no, the code that will be executed is this:

log ""

It auto-fills the space for you.

This code, as is, will print out to the "Messages" tab in Script Editor or to STDERR through osascript -e.

log

Length 6 Snippet

repeat

While this won't run on its own (it needs an end statement), this is one of the most important keywords in AppleScript - on its own, with no restrictions on how many times it will repeat, it will loop infinitely. The syntax relating to repeat is immense, so I won't mention it all in this snippet. It'll come back later, though.

Length 7 Snippet

try
end

Error catching in AppleScript. Piece o' cake. This may be used in instances where you are comparing possible null strings to other strings or when trying to see if true > 5. It's also very important syntax, but used less frequently in the code golf community.

Length 8 Snippet

activate

Let's say you've lost the primary window of an application, or you want to start it. If you tell an application, even one that isn't active, to activate, it will move to the pane where it was last open (or currently open) and pull up any active windows (or start them if the application wasn't active until the point at which you told it to activate).

Example code that actually is relevant:

tell app"Finder"to activate

Runs as

tell application "Finder" to activate

Which makes the "Finder" application the primary application (for MacOSX users, this means that it's the application name in the top-left hand corner. It might have no active windows).

finder

Length 9 Snippet

keystroke

This is a command that's typically specific for the application 'System Events' - basically, it replicates the user of typing in a character.

keystroke

Length 10 Snippet

set x to 1

Finally.

This is how you make variables in AppleScript. Due to its verbosity, many answers for languages like CJam or Pyth will be shorter than just the variable declaration. This is why AppleScript will almost never win at golfing.

Still, though. The fact that it's also pseudocode is nice.

Length 11 Snippet

if 1<=1
end

A simple if statement.

This will execute as

if 1 ≤ 1
end if

Thanks to AppleScript autocorrection and bonus(!) supported characters. This is the most basic (and most concise!) syntax for if statements in AppleScript.

Note: This is actually shorter than if <conditional> then, the one-line way to do it.

Second note: Because of the extreme verbosity of AppleScript, the "correct" way to do this is with less than or equal to, but it will support <= or ≤ anyways.

Length 12 Snippet

current date

Wonder what this one does...

current date

Length 13 Snippet

the clipboard

You can gather the contents of the clipboard fairly simply with this command; when called anywhere, it will return the value of what's held currently in the clipboard. It's brother, set the clipboard to, does exactly as it sounds.

clipboard

Length 14 Snippet

You know a language is verbose when the first method of input through scripting is 32 bytes long.

clipboard info

I'm not even sure what this one is... The documentation about it simply says:

Returns information about the clipboard.

¯\_(ツ)_/¯

This is a result for a clipboard that has been set to "" with the command set the clipboard to ""

clipboard2

Length 15 Snippet

Who knew AppleScript was so sassy?

summarize string

I honestly have no clue what the point of this command is. When called on datatypes, though, it does some funny things.

string

'A string is pretty much "TEXT"'

cappa

'Kappa, you don't know what an application is?'

doubt

'I'm kinda doubtful of reality.'

...and nihilistic, too? I'm learning a lot about AppleScript. >.>

Addison Crump

Posted 2015-01-19T12:36:59.320

Reputation: 10 763

seems like the "keystroke" snippet showcases the "current date" feature – Ven – 2016-04-26T13:34:34.303

1@ven Whoops, I'll fix that. Thanks. – Addison Crump – 2016-04-28T07:05:46.757

117 votes. Please update your answer ASAP. (don't panic though) – Erik the Outgolfer – 2016-05-30T06:59:42.837

22

Lisp

Factoid

Lisp is defined by its unique parenthetical notation.

Snippet (10 chars)

(+ 1 1 10)

Ok, I know I've been using + for a while now, but now this will show another side of it. One time, I showed + with 0 parameters, then 1, and now 3. This will return 12.

Snippet (6 chars)

(main)

If you're deciding to compile lisp, usually you would define the function main. This simply executes that. Otherwise it would throw an error.

Snippet (5 chars)

(+ 1)

Similarly to the three-character snippet, this adds one to nothing. It seems it should show an error, but instead, simply returns 1.

Snippet (4 chars)

(ex)

Because ex is a function not defined by default, the interpreter will throw an error.

Snippet (3 chars)

(+)

+ is a function that adds all of the parameters. Because this is adding nothing to nothing, you would expect this to return an error or nil, but it actually returns zero.

Snippet (2 chars)

()

This is the shortest functional snippet. It simply returns nil.

Snippet (1 char)

;

This does absolutely nothing. It is simply a comment. There is nothing that functions in Lisp that has less than two characters. (maybe reading the Factoid would help?)

robbie

Posted 2015-01-19T12:36:59.320

Reputation: 427

1"Unique" is one word for Lisp's parentheses. I'd probably go with "excessive." :) – Alex A. – 2015-02-21T04:14:46.593

1@Alex Say what you wish. I stand by Lisp. – robbie – 2015-02-21T14:42:48.453

Don't get me wrong, I think Lisp is great. Just lots and lots of parentheses. – Alex A. – 2015-02-21T23:13:49.733

1@Alex Lots of parentheses, but it's better than having all these parentheses, square brackets, and curly brackets all over the place. – robbie – 2015-02-22T02:06:56.723

22

Hexagony

Hexagony is a 2D esoteric language made by Martin Büttner based on hexagons. Not only the programs self are hexagons, but the memory model of terror is also based on hexagons. It took me quite some time to understand the model of terror, but eventually I still don't get it. First time I programmed in this, I was happy to get anything outputted, but after a while I realised that this is a very interesting language, with a lot to discover. I would definitely recommend programming in Hexagony.


Length 1 snippet (try it here)

!

Or in hexagon form:

!

Let's talk a bit about the memory model in Hexagony. Every memory edge has a standard value, 0. This is different from some other models, which are standard null. The second thing which makes this memory model different, is that the data kept in the memory edges are always numbers. No strings, lists, tuples and so on. For this program, I'm going to introduce you to the command !. This outputs the decimal representation of the current memory edge. ; would do the same thing, but outputs the ASCII representation.

So, you can already expect what this is going to do. This is going to print an infinite amount of 0. After running in the online interpreter, immediately kill it. It won't stop, ever.


Length 2 snippet (try it here)

!@

Or in hexagon form:

 ! @
. . .
 . .

So, you might be wondering... When can you make this stop? That is done with the @ command. After reaching this point, the program terminates. That means we can now safely output one 0 with the program. Another thing you might be wondering is 'What are all those dots doing there?'. That brings us to the next command, the no-op .. When the pointer comes to a no-op, it will not do anything and continues its way in the same direction. This means that !@ and !@... and !@..... are all the same and give the same output. However, if we add another dot: !@......, this would give a bigger hexagon, since the maximum amount for a two-sided hexagon is smaller than the length of the program. It would give the following:

  ! @ .
 . . . .
. . . . .
 . . . .
  . . .

Length 3 snippet (try it here)

9!@

Or in hexagon form:

 9 !
@ . .
 . .

First of all, decimals in the program will be added to the current memory edge. If the memory egde = 402 and passes by a 3, the new memory edge will contain 4023. Same counts for letters, which replaces the memory edge with the ASCII value of the letter. I'll now explain how pointers move in Hexagony. But first of all, there isn't just one pointer. There are six. Each in every corner:

  0 . 1
 . . . .
5 . . . 2
 . . . .
  4 . 3

They all point clockwise, so 0 would go to the east (E), the 1 would go to the southeast (SE) and so on. The standard active pointer is 0, and you can switch the active pointer using the [ and the ] command. The next thing is, what happens when they get out of the board? When they leave at a non-corner point, they will enter the board again in the other half of the program (pointer starts at A):

   . . . .        . F . .        . A . .        . . A .
  A B C D E      . . G . .      . B . . F      . . B . .
 . . . . . .    A . . H . .    . C . . G .    . . C . . G
. . . . . . .  . B . . I . .  . D . . H . .  . . D . . H .
 F G H I J K    . C . . J .    E . . I . .    . E . . I .
  . . . . .      . D . . K      . . J . .      F . . J .
   . . . .        . E . .        . K . .        . . K .

If the pointer leaves from a corner, it depends on what value the current memory edge has (from A to B):

                     memory > 0            memory <= 0

     . . A ->          . . .              -> B . .
    . . . .           . . . .               . . . .
-> B . . . .         . . . . A ->          . . . . A ->
    . . . .           . . . .               . . . .
     . . A ->       -> B . .                 . . .

So the order of operations in this program is 9, !, @, which will output 9.


Length 4 snippet (try it here)

!$!)

Or in hexagon form:

 ! $
! ) .
 . .

First, it begins at the top left !, so this will output 0. After that, it goes to the $, which is a jump. This will skip the next command, which is !. So the 0 isn't outputted twice. After that, the pointer gets to the ). This is an increment command, which just adds 1 to the current memory edge. After that, the pointer leaves the hexagon in the right corner and re-enters at the bottom left (see previous snippet to see why). As you can guess, this will output 012345678910111213141516171819202122232425....

After running in the online interpreter, immediately kill it, it won't stop.


Length 5 snippet (try it here)

H;i;@

Or in hexagon form:

 H ;
i ; @
 . .

This one is quite easy and simple. First, the pointer gets to the H, which pushes the char value of H. The ; will output the char H. After that, when the pointer comes to the i, the value of the memory edge will be replaced by the value of i. This will be printed by the second ; and terminates because of the @.

This will output Hi.


Length 6 snippet (try it here)

40;);(

Or in hexagon form:

 4 0
; ) ;
 ( .

The new thing here is that it appends two different numbers to the memory edge. After going through the 4 and the 0, the memory edge has the value 40. This is in ASCII (. After that, the program will output this character and adds one up to the memory edge. That gives us 41, which is the closing parenthese ()). After outputting this character, the program decreases the current memory edge by 1 and goes into an infinite loop. The output will look like this: ()()()()()()()()()()...

After running in the online interpreter, immediately kill it, it won't stop.


Length 7 snippet (try it here)

?}?"*!@

Or in hexagon from:

 ? }
? " *
 ! @

This is where the memory model of terror begins. What this does is taking 2 integers (these have to be positive or both negative), multiplies them and outputs the result. I'll explain this with the hexagonal memory model:

enter image description here

In the beginning, the memory model starts at the a. The ? pushes the input onto the memory edge a. After that, the } switches to the right memory edge, which is b. There we push the input to the memory edge b. The " moves the memory pointer backwards and to the left, which is c. The * calculates the product of the two neighbours, which are a and b, prints it and terminates.

In pseudocode:

a = input()
b = input()
c = a * b
print(c)
end

Length 8 snippet (try it here)

/+!=/1}~

Or in hexagon form:

  / + !
 = / 1 }
~ . . . .
 . . . .
  . . .

Yes, this gives us a size 3 hexagon. That is because the program can't fit in a size 2 hexagon. In the hope to create a Fibonacci sequence, I ended up with this. It gives the following sequence:

11213214421574217184218758422047684222352684224400368422...

I don't even know how this can output something. I probably made a mistake in my head or something, because I can't visualize what is actually happening.

Thanks to FryAmTheEggman, this does output something Fibonacci-like:

1
12
132
1442
15742
171842
1875842
20476842
223526842
2440036842

The end part is always the same (2, 42, 842, 6842). This is quite interesting and I'll try to find a more describable pattern.

After running in the online interpreter, immediately kill it, it won't stop.

Adnan

Posted 2015-01-19T12:36:59.320

Reputation: 41 965

I'm upvoting this, even if it means beating my answer. Hexagony is so fun! – ev3commander – 2015-12-17T20:27:04.850

Fibonacci can be done in 6 with no separator, and 18 with, afaik.

– FryAmTheEggman – 2015-12-18T18:15:27.463

I've figured out what your code is doing, each time it goes around the loop, the 1 is messing up your logic. The values being printed out are: 1, 12, 132, 1442, 15742 ... – FryAmTheEggman – 2015-12-18T20:04:17.480

1+1 for "I still don't get it" – Mego – 2016-01-15T07:27:37.030

I was revisiting a bunch of these, and I realised that I never explained what was happening. Oops :P Anyway, your code does: F_n = (10 * F_n-1 + 1) + (10 * F_n-2 + 1). – FryAmTheEggman – 2016-04-05T03:03:23.657

Very interesting. In general Hexagony has been one of my favorite programming languages posted on PPCG. I have never used it myself, but it's a very original language. I would love to see a few more snippets since you are currently at length 8 & upvotes 20. – Kevin Cruijssen – 2016-09-07T14:15:03.663

21

Delphi (also known as Object PASCAL)

Factoid: Over the years the name of Delphi changed prefixes many times. Beginning with Borland Delphi. This name held for ~13 years until it got renamed to Embarcadero Delphi in 2008 (as you may assume Embarcadero bought Delphi).
The code is similar to C++, but is more object oriented and is translated from PASCAL to C++ during compilation. Recent versions are also able to generate applications for all major OSes including Windows, OSX, Linux, Android and even iOS.

Downsides are: Delphi is built together with VCL (Visual Component Library) which slows down the performance of graphic-heavy applications a lot (every change of properties of a visual object will cause a redraw of the component), but the IDE is even simpler to use (drag and drop of components).

Notes:

Because a line-ending semicolon (;) is optional before a closing end; tag, I may omit it to save characters.

Length 1:

;

Yes, I know. It's very basic, but is compiled without throwing errors, warnings etc.
It will be compiled into a simple NOP statement doing nothing.
This may be helpful, if the IDE removes empty procedures, to make sure you remember to program them.

Length 2:

1:

D;

This will simply run the procedure D without any arguments. In Delphi there is no distinction of lower- and uppercase names (functions, procedures, variables even files in the compiler directive) and functions or procedures (two different types of jumping to code and returning back) can be called as well as be declared without braces (()) if they don't request parameters.
This above means, that the procedure/function could be called either d or D and could be declared with or without braces. The compiler takes care of managing this.

2:

L:

This places a label at the current location. You can then use goto L; to jump to that label, which allows skipping code or alternative loops.
You just need to make sure that you declared the label in the function/procedure head (label L;)

Length 3:

asm

Yes, Delphi allows inline assembly code!
This snippet is the opening tag for assembly code, but have to close it with end; of course else it will spam compiler errors.
Inside the asm [...] end; block you can use your beloved assembly with all the variables used in usual Delphi.

Length 4:

Date

or

Time

Those two are functions returning the actual date or time of the day of the type TDateTime. Funny enough TDateTime is just an alias for Double with no changes at all. Using DateToStr or TimeToStr every Double can be converted into the actual Date/Time.

Length 5:

Free;

Bam! This procedure frees the current object (ie. safely destroying it). If you do it on one of your forms this closes the window but keeps the process (event queue, primary thread etc.) running. If an object is currently being created, calling Free; will throw an access violation error.

Length 6:

goto l

(Assume l is an already defined and set label)
Tired of while True do loops? Use labels and gotos!
If you put a call in the line before an end; you don't need a line-ending ; (semicolon). Very handy.

Length 7:

Swap(8)

Some bitwise operations, yay! This function swaps the first half of a SmallInt (16 bits) and the second half. Example: 8 (0000 0000 | 0000 1000) becomes 2048 (0000 1000 | 0000 0000).
It doesn't matter which size the integer actually has, it gets converted to a SmallInt by truncating/filling with zeros.

Funny side-note: Usually all functions are declared anywhere, especially when exploring their declaration, but Swap (as well as a few others) are not found in the source of their declaration file (System.pas) but the declaration is displayed correctly.

Length 8:

Repaint;

If you call this in a component's thread (which is usually your main thread), this will schedule all child components and itself for repainting. This is usually not needed, but if you modify components outside of the main thread (eg. in a secondary thread) the components do not get invalidated nor repainted, thus needing this procedure. This procedure also has an alias called Refresh;.

Length 9:

1:

Trim(' ')

This function takes a string and trims (ie. removes) all leading/following spaces (no other character(s)) and returns the trimmed string.
There are even functions to trim only one side (left or right).

2:

{Comment}

Right, Delphi doesn't use curly brackets in code, but rather as the opening/closing tag of a comment. There are two types of declaring a comment:

  1. curly brackets like above ({}).
    They allow multi-line comments. You can replace those curly brackets with (* *), if you are not able to use those.
  2. double forward slashes (//).
    Many languages feature them, so does Delphi. The end of the comment is the next line break, so use this for small notes.

Length 10:

{$R *.dfm}

"What is this?", you might think. It seems like a comment I just characterised above. But it isn't;
it's a compiler directive! It tells the compiler to add a file named the same as this Unit (that's how source files are called in Delphi), but with the extension .dfm, which is the common file type of a form.
Compiler directives can be identified by the $ as the first character in curly brackets.

Length 11:

SendToBack;

Some more things you can do with windows/forms you have control of (which should be all of them; unless the system denies permission, which may happen on windows owned by processes of the System user).
This procedure will put the window to the back of the stack without losing focus. This may be useful for something, but hiding a form/window moves the focus to the next one and doesn't keep the actual window open and focused.

GiantTree

Posted 2015-01-19T12:36:59.320

Reputation: 885

21

Kotlin

Kotlin is a statically-typed programming language that runs on the Java Virtual Machine and also can be compiled to JavaScript source code. Its primary development is from a team of JetBrains programmers based in Saint Petersburg, Russia.

Factoid: The name comes from the Kotlin Island, near St. Petersburg.

Length 1 ?

Kotlin has built-in null safety. A normally declared variable cannot contain a null value, unless that type is declared with the modifier ?. For example, var a: String = "sam"; a = null is an error at runtime. However, var a : String? = "sam"; a = null is legal.

This extends to parameters, where a possibly-null variable cannot be used where a not-null variabled has been specified.

Length 2 ?.

Kotlin allows us to chain methods together, with a short cut for nulls. So, if we did val myBoss = employee?.department?.boss?.name then, if any of the intermediate calls were null, the final result would be null and not a null pointer exception.

Length 3 out

Kotlin supports declaration site variance like Scala, but using the out keyword rather than +. In scala, trait Foo[+T] makes Foo covariant in T, in Kotlin the equivilent would be trait Foo[out T], similar to how C# does it. The idea being that a covariant type only produces values of T (outputs them), so the naming convention makes it easier to remember which way around co-variance and contra-variance work.

Length 4 data

The data keyword is used to create a data class. Eg, data class Foo(val a: String, val b: Int). The compiler automatically generates the following functions from all properties declared in the primary constructor with a val or var: equals() / hashCode() pair, toString() of the form "Foo(a="qwerty", b=42)", componentN() functions corresponding to the properties in their order or declaration, and a copy() function.

If any of these functions are manually defined in the class body or inherited from non trivial parent types, they will not be generated.

Length 5 c.foo

Extension methods are methods that can be added to an already existing type. To declare an extension function, we need to prefix the name of the method with the type we wish to extend. Eg, the following adds a method to String called take:

fun String.take(k : Int) {
 ....
}

Note, this inside the function refers to the receiver object. Eg, when invoking string.take(4) the this would refer to the string instance.

Length 6: inline

We can ask Kotlin compiler to inline a function, so that the overhead of wrapping a closure in an object does not occur.

Eg, given

inline fun lock<T>(lock: Lock, body: () -> T): T {
  // ...
}

Then

lock(l) {foo()}

Would be compiled into

lock.lock()
try {
  foo()
}
finally {
  lock.unlock()
}

Length 7: a !is B

Kotlin does not require explicit casts, but instead will smart-cast a type once an is or !ischeck is performed. For example:

// given a x of type Object
if (x is String) {
   println(x.substring(3)) // x is automatically cast to String
}

Now get this; the compiler is even smart enough to understand negative casts that lead to a return. For example:

// given a x of type Object
if (x !is String) return
// from here, x is available as a String
println(x.substring(3))

That's pretty cool.

Also Kotlin does allow unsafe casting if needed, using the as keyword. It will throw an exception if the cast cannot be performed. Eg,

val y : String = x as String

Length 8: when (x)

When is somewhere between simple switching and pattern matching. A when block will match its argument against each branch until some branch condition is satisfied. The when block is an expression so yields a value. The default case is declared with the else keyword but is not needed if the compiler can see that all cases are covered. One difference with Scala here is that the branches can invoke method calls directly (with Scala we would move that to a guard clause on the case branch).

An example:

val k :String = ... // some string

when (k) {
  isUppercase(k) ->
  isLowercase(k) ->
  else ->
}

monkjack

Posted 2015-01-19T12:36:59.320

Reputation: 423

21

CSS

Length 18 snippet

(min-width: 700px)

This is part of a media query, which allows certain styles to only show for certain media. Perhaps the most common is min- and max-width, which is the basis of responsive web design, allowing the site to look different depending on the device width. While a news site might expand to fill a widescreen monitor by fitting several stories next to each other, on a phone there is only enough room for one.

The most common way of using media queries is within a stylesheet: the rules are surrounded by {} brackets, prefixed with @media ([rule]), like so: (click "Full page" to see the background color change from tomato to turquoise)

body {
  background-color: tomato;
}

@media (min-width: 700px) {
  body {
    background-color: turquoise;
  }
}

Media queries can also tell you even more data about a device, such as its resolution, color, and orientation.

Length 15 snippet

input:checked

Another pseudo-selector, this selects all <input>s that are checkboxes (or radio buttons or dropdown options) that have been selected by the user. This gives CSS an unintended way to register clicks, allowing for everything from tabs to a reaction time test.

These work by having a <label> for the checkbox that checks the box when clicked anywhere on the text. The checkbox is hidden, leaving just the label. Then the adjacent sibling selector + is used to select the label. Here is a simple example (click "Show code snippet").

input:checked + label {
  font-weight: bold;
  color: red;
}

input {
  display: none;
}

label {
  display: block;
}
<input type="radio" name="foo" id="radio1" />
  <label for="radio1">Click me!</label>

<input type="radio" name="foo" id="radio2" checked />
  <label for="radio2">Click me!</label>

<input type="radio" name="foo" id="radio3" />
  <label for="radio3">Click me!</label>

Length 14 snippet

columns:4 12em

CSS has the ability to break up long text into several shorter columns, as commonly found in newspapers. The columns property above is shorthand for column-count: 4; column-width: 12em, which tells the browser to break the text into at most 4 columns, at least 12em wide. There are more related properties that allow you to control other aspects, such as gap and rule between columns.

Length 12 snippet

display:flex

This is the code to make flexboxes, which do just what you think: make boxes flexible. This does away with hacky methods developers used and adds a lot of functionality. CSS-Tricks has an excellent guide to all things flexbox that explain them in more detail.

Length 11 snippet

:last-child

This is a pseudo-class that selects each element that is the last child of its parent. For example, take the following HTML code.

<section>
  <p>Foo</p>
  <p>Bar</p>
  <p>Baz</p>
</section>

A selector of p:last-child would match the Baz paragraph because it is last. However, if there were a different element, say <blockquote>, after Baz, that selector would match nothing because there is no <p> that is the last child. For this, you would use p:last-of-type, which ignores all non-paragraph elements and finds only the last <p>, regardless of whether it is last overall.

A useful cousin of this selector is :nth-child. It is clear that :nth-child(3) would match the third element, but you can also use more complex queries, such as :nth-child(2n+1), which matches every other element. This is useful for styling every other row of a long table for easy contrast. Mozilla Developer Network lists several ways to powerfully use nth-child.

Length 10 snippet

!important

This causes other, more specific rules to be overridden. It is placed after a declaration, before the semicolon. Note that in most situations, you should not use this, because it can make debugging a nightmare, but I will take this opportunity to talk about specificity, which is where the "cascading" in CSS's name comes from.

This basically means that a declaration that applies to a few elements (i.e. it's more specific) will be used in favor of a declaration that applies to more elements. For example, take these HTML and CSS snippets (click "Run code snippet" to see what happens):

.green { color: green; }
#red { color: red; }
* { color: blue; }
p { color: yellow; }
<p class="green" id="red">Foo bar</p>

You'll notice that even though all three rules match the <p> element, the red color gets applied because it is the most specific: as mentioned below: #red is an ID, which should be unique to only one element, while you can have any number of green classes or <p> elements. The complete specificity order is found in the Mozilla Developer Network page linked above. In the following snippet, nothing has changed except for the addition of !important, but it causes the universal selector, which is the least specific, to take precedence over all the others.

.green { color: green; }
#red { color: red; }
* { color: blue !important; }
p { color: yellow; }
<p class="green" id="red">Foo bar</p>

Length 9 snippet

max-width

This property is pretty self-explanatory: it defines the maximum width an element can have. One common example usage is for a webpage that has large amounts of text, such as a blog post or news article. You would want the text to take up as much horizontal space as possible on any device, so you'd set the width of each paragraph element to 100%. However, on wide screens, lines become too long to navigate comfortably, so you might set the max-width to 1000px so the width stops increasing after the window is wider than 1000 pixels. Predictably, there are also min-width and max-height properties.

Length 8 snippet

q::after

This creates a pseudo-element (slightly different from the pseudo-class in the length 6 snippet below) after every <q> element, which can be separately styled from the <q> itself. This is commonly used with the content property, which allows you to add text that will show up after the element. <q> is used to designate inline quotations, so you would add the declaration content: '"' to automatically add quotation marks after every quote.

As you might guess, there is also a ::before pseudo-element which does the same thing, except before the element. The two of these working together can be used to make all sorts of shapes like a heart or star using only one HTML element and CSS (which is based on the box model). You can see many of these and their code on CSS-Tricks.

Length 7 snippet

b{top:0

This is one of the shortest possible full "programs" that can actually do something. It demonstrates the format of a CSS rule: before the braces is the selector, which is usually an HTML tag, class, or ID, but it can also be more advanced, like some of the snippets below. The b in this example selects every HTML <b> (bold text) element.

The inside of the braces are the declarations. (The closing brace of the last rule is optional.) Each declaration is a pair of property and value, separated by semicolons (again, the last semicolon is optional). In this example, top is the property, 0 is the value, and they are separated by a colon. A more readable and realistic version of the above would be:

b {
  top: 0;
}

Length 6 snippet

:hover

This is a pseudo-class selector that is applied when an element is hovered over with the mouse. You see this all the time, for example in comments on a Stack Exchange site that show upvote and flag buttons on hover, or links that change color when you mouse over them. There are other state selectors like active, focus, and visited.

Length 5 snippet

[alt]

This is a selector to match any element with the alt attribute (most often used for specifying alternative text if an img cannot be displayed), regardless of what it is or if it is empty. You can use [alt=foo] to only match elements with an alt value of foo. There are several others for attributes containing, beginning with, and ending with a value.

Length 4 snippet

#38b

CSS uses hex triplets to specify color, which consist of three two-digit hexadecimal numbers, two each for the amount of red, green, and blue present in the color. If both digits in each set are the same, as in #3388bb, it can be shortened to just the first digit of each, as in the snippet above. There are 224 = 16777216 possible colors. The color is shown below:

#38b

Length 3 snippet

p#s

This matches a <p> (paragraph) element with the ID s. IDs are similar to classes, which are explained below, except classes can be used on any number of elements and an element can have multiple classes, whereas each ID should only be used once, and elements can only have one ID.

IDs can also be used as targets, where a link to an ID links directly to that element on the page. For example, a link to this question ending in #49172 will link directly to this answer, because it has ID 49172. You can chain IDs and classes: .a#b.c matches an element with ID b and classes a and c.

Length 2 snippet

.a

This matches an element with the class a, used for styling multiple instances of a style. For example, you might use <a class="external"> for styling only external links, different from all links.

Length 1 snippet

*

This is the universal selector. It matches any element on the page, although it is the most expensive selector.

Factoid

CSS (Cascading Style Sheets) is not your typical programming language, as it is used for styling HTML web pages, but I thought it still would be interesting for this challenge.

CSS came at a time when design on the Internet was a mess, with designers abusing HTML for styling purposes (<table> has never been the same). Adoption wasn't consistent across browsers, causing headaches for designers who had to resort to "hacks" to get their code to work cross-browser. These different implementations continue to this day, although much better, in the form of vendor prefixes.

NinjaBearMonkey

Posted 2015-01-19T12:36:59.320

Reputation: 9 925

Maybe show off your color! ![](http://dummyimage.com/100x100/38b/38b.png) – Lynn – 2015-05-12T15:45:44.477

21

MATL

Factoid

MATL is a stack-oriented language based on MATLAB and suitable for code golf. Many functions are similar to those of MATLAB, sometimes with extended funcionality.

To simplify stack handling there are clipboards, similar to variables in other languages. An interesting feature is an automatic clipboard that holds the inputs of recent function calls. This often avoids the need to manually copy.

There are different types of functions. Most are normal functions, which perform operations on inputs and produce outputs. Other types are stack-handling functions, for duplicating, deleting or moving elements in the stack; and clipboard functions, for copying and pasting elements from the clipboards.

Length 1: sum of elements in an array

The program (try it online!)

s

computes the sum of an array provided as input and displays it. This serves to illustrate several things:

  • Input can be implicit: if a function needs an input that is not present in the stack, it is automatically taken. The explicit form would be is, where i takes the input.
  • The stack contents are implicitly displayed at the end of the program, by default.
  • MATL, like MATLAB, has many operations that automatically operate on the contents of an array. Using terminology of other languages, s folds the addition operation over the array.
  • If the input to s is multidimensional, this function performs the sum along the first non-singleton dimension, as in MATLAB. For example, if the input is a 3×4 array (use ; as row separator), the output will be a 1×4 row array (sum along first dimension). If the input is a 1×4 row array, the result will be a 1×1 array (sum along second dimension), which is the same as a number.

Length 2: sum along columns

So what if we want the sum of each column, even if the input happens to be a row array? The following code (try it online!) does that:

Xs

These two characters together are the name of a single function, which in this case is "sum along the first dimension". Functions are always defined by either one or two characters, and in the latter case the first character is always X, Y or Z.

Another form of forcing the sum to operate along the fixed dimension would be to use the s function with two inputs, and specify the desired dimension as second input (see length-3 snippet).

Length 3: ternary range

3$:

Try it online!

Many functions can take a variable number of inputs or outputs. Each function has a default number of inputs and outputs, or arity. These default can be modified by means of meta-functions. The meta-function $ specifies the number of inputs (or even their position in the stack) of the following normal function.

The function : (range) by default takes one input n, and produces its unary range. With three inputs, say i, s and f, it produces an array formed by numbers i, i+s, i+2*s, ... up to the largest integer not exceeding f.

Length 4: multiplication table

The code (try it online!)

:t!*

produces an n×n multiplicaton table, where n is an input number.

  • : by default it takes 1 input, and produces the row array [1,2,...,n].
  • t is a stack-handling function. It also takes 1 input by default, and simply duplicates it. Other stack-handling functions are w (swap elements) and b ("bubble up" and element).
  • ! is transposition, so the row array at the top of the stack becomes a column array [1;2;...;n].
  • * corresponds to multiplication. By default it takes two inputs. Like most arithmetic operators, it works element-wise with broadcast.

The latter means that repetition is implicitly applied along singleton dimensions if needed. In this case, the two arrays have non-matching dimensions 1×n and n×1. Thus the first array is implicitly replicated n times along the first dimension, and the second along the first dimension, so that they can be multiplied element-by-element. This produces all "combinations" (in the sense of Cartesian product) of the operation.

The result is a 2D numeric array. Numeric arrays are displayed as numbers separated by spaces with vertical alignment.

Length 5: display "all" even numbers

`@EDT

This uses an infinite loop, specifically a "do...while" loop in which the loop condition is always true. Try it online! (but kill it immediately).

A "do...while" loop begins with ` and ends with ]. "End" statements ] at the end of the program can be omitted, because the loop is implicitly closed in that case.

In a "do...while" loop, when the (possibly implicit) statement ] is reached the top of the stack is consumed, and if it's truthy the code proceeds with the next iteration. An array is truthy if and only if it is non-empty and all its elements have nonzero real part. In this case a T literal (true, corresponding to a logical 1) is pushed at the end of each iterartion, so the loop goes on forever.

The body of the loop pushes the iteration index with @. Note that iteration indices start at 1. Then E doubles that number, and D displays it. In this case we cannot rely on implicit display at the end of the program, because this program never ends.

Length 6: Separate primes from non-primes

tZp2#)

This code accepts as input an array of positive integers, and produces two arrays: one with the primes contained in the input, and one with the non-primes. Try it online!

The code is based on logical indexing, which means using an array of type logical as an index. This works as in MATLAB: true values in the index specify which entries to use. So for an array [10 20 30 40], the index [false true false true] refers to the subarray formed by the second and fourth entries, that is, [20 40].

If we wanted to only pick the primes from the input, the code would be tZp): duplicate the input (t), check for each entry if it's a prime (Zp), and then use the second array as an index into the first ()).

) is one of the several indexing functions in MATL. Specifically, it does reference indexing, which means extracting elements from an array. (This contrasts with assignment indexing, whereby specified positions of an array are written with new values). The ) function, like others used for reference indexing, has a two-output version, which produces the indexed array and the "complementary" array, corresponding to the entries not selected by the index. The meta-function # specifies the number of outputs of the following normal function. So in this case 2#) produces the primes and then the non-primes in separate arrays.

Length 7: Separate digits from non-digit characters

t4Y2m&)

This snippet is similar to that with length 6, but serves to illustrate two new aspects: predefined literals and meta function &. The code takes a string and separates it into two strings: one formed by the digits and one with the non-digits, in the same order. Try it online!

Y2 is one of several functions that produce predefined literals depending on its numeric input. In this case, 4Y2 gives the string '0123456789'. Function m takes two inputs by default, and outputs a logical array that contains true for elements of the first input that are present in the second. This is then used as logical index into the original string, which was duplicated (t) at the beginning.

2#) would then produce a substring with the digits and then a substring with the remaining characters. But &) can be used instead.

Most functions allow an alternative or secondary default input/output configuration. Meta-function & is used for this purpose. For ), using & corresponds to selecting two outputs, so &) is equivalent to 2#). Thus the code produces the indicated result.

The meaning of & is function-specific. For example, for : it affects the number of inputs. A way to see this is to display the function's help using option -h of the compiler:

>> matl -h :
:   vector of equally spaced values
    1--3 (1 / 2);  1
    colon (with three inputs x, y, z produces x:y:z; with two inputs 
    x, y produces x:y). If one input: produces 1:x 

The line 1--3 (1 / 2); 1 describes the possible numbers of inputs and outputs. This function takes a variable number of inputs from 1 to 3, and produces 1 output. The default number of inputs is 1, and the effect of & is to change that to 2.

Length 8: filter square-free numbers

The code

"@YfdA?@

takes an array of integers and outputs those integers that are square-free. A number is square-free if it can't be divided by a perfect square other than 1. Equivalently, in the prime factor decomposition of a square-free number no prime appears more than once. This code serves to illustrate some control flow structures, namely for loops and if branches. Try it online!

Statement " begins a for-each loop: it takes an array as input and iterates over its columns. Within the loop, @ pushes the current iteration variable, that is, each column of array. In the present case the input is a row array, so each column is just one number. Yf takes that number and pushes its prime factors. d computes the differences between consecutive elements, so a square-free number will not produce any 0. A with a vector as input gives true if all the elements are nonzero. So the output of A tells if the current number is square-free or not.

Following is an if branch: ? takes an input and if truthy executes the next statements. In this case there is only one statement, @, which pushes the current number (which was found to be square-free).

Control flow structures are normally ended by ]. In this case, the two ] statements are implicit at the end (as in the length-5 snippet). Using the compiler with the -e option shows the code including the implicit statements, as well as automatic comments, which may be useful as a starting point for an explanation of the code, with indentation:

>> matl -e "@YfdA?@

"          % for
  @        % for loop variable
  Yf       % prime factors
  d        % difference
  A        % all
  ?        % if
    @      % for loop variable
           % (implicit) end
           % (implicit) end
           % (implicit) convert to string and display

Length 11: Matrix multiplication, manually

7L&!*Xs6Be!

This illustrates the use of multidimensional arrays. These are a powerful tool, specially when coupled with dimension permuting and broadcasting. The code takes two matrices and computes their matrix product (which could be computed with the builtin Y* function). Try it online!

Function 7L pushes the predefined literal [2 3 1], and &! applies that permutation of dimensions to the first (implicit) input. Let this input be an M×N matrix (2D numerical array). The permutation with [2 3 1] means that the 2nd dimension becomes the first, the 3rd becomes the second, and the 1st becomes the third. Since the input is a matrix, its 3rd dimension is actually a singleton dimension, that is, the size along that dimension is 1. In fact, any array can be assumed to have arbitrarily many trailing singleton dimensions. So the input matrix can be interpreted as an M×N×1 3D array, which after the permutation becomes an N×1×M array.

Function * takes a second (implicit) input and multiplies it by the previously obtained 3D array. The multiplication is element-wise with broadcast (see length-4 snippet). The second input has size N×P, or equivalently N×P×1, and the result of * has size N×P×M. To obtain the matrix product, a sum is carried out along the first dimension using Xs. Note that the first dimension of the N×P×M array corresponds to columns of the first matrix and rows of the second. The result of Xs has size 1×P×M.

6B pushes 6 in binary, that is, the logical array TTF (or [true true false]). Then e is applied to collapse the first two dimensions of the 1×P×M array. This works as follows. e is used for reshaping arrays, and takes two inputs by default. With a logical array as second input, it collapses consecutive dimensions of the first input that have the same logical value in the second. So in this case it collapses first and second, producing a P×M matrix.

Finally ! transposes the matrix to yield the M×P final result.

Length 12: show a simple image

The code

:i:!+t0)/3YG

takes two inputs and shows the following image (example for inputs 200, 150). Try it at MATL online!

enter image description here

: takes an input w and generates the row vector [1 2 ... w]. i:! takes a second input h and produces the column vector [1; 2; ...; h]. + creates an h×w matrix with all pair-wise additions.

t0) creates a copy of the matrix and extracts its last element. This uses linear indexing: a single index is used to access a two-dimensional array (matrix) in column-major order, i.e. down, then across. So for a 2×3 array the linear indices would be

1 3 5
2 4 6

The index is interpreted in modular sense. This means that indices out of bounds are interpreted cyclically. The period of the cycle is the size of the indexed dimension; or, for linear indexing, the total number of elements of the array. So in the 2×3 example a linear index 8 is the same as 2. 0 always corresponds to the last value in linear order, that is, last column and last row.

Thus t0) is the last element of the h×w matrix of pair-wise additions. By construction, this is the largest value. So the following / normalizes the array to maximum value 1. Finally, YG is a function for displaying or saving images. With second input 3 it displays the matrix with each entry corresponding to one pixel on the screen, using a grey colormap by default.

Luis Mendo

Posted 2015-01-19T12:36:59.320

Reputation: 87 464

2.......5 and 6? – Conor O'Brien – 2016-04-04T22:29:14.693

1@CᴏɴᴏʀO'Bʀɪᴇɴ :-) 5 is almost ready. I hope I'll have time tomorrow! – Luis Mendo – 2016-04-04T22:30:36.170

@CᴏɴᴏʀO'Bʀɪᴇɴ 5 included. Currently thinking about 6... – Luis Mendo – 2016-04-05T22:42:51.963

7, 8, 9, 10, 11? – CalculatorFeline – 2016-04-30T03:33:31.147

@CatsAreFluffy Working on that :-) – Luis Mendo – 2016-05-01T02:44:52.610

ouch wut a pain, lemme thirteenfold it for you :D – Abr001am – 2016-05-27T19:36:59.753

@Agawa001 Manual matrix multiplication added :-) – Luis Mendo – 2016-05-27T21:51:08.157

@CalculatorFeline I've added some snippets – Luis Mendo – 2016-06-02T21:42:14.767

13, 14, 15, 16? – OldBunny2800 – 2016-11-23T15:56:13.450

@OldBunny2800 I haven't had any idea for those yet... :-) – Luis Mendo – 2016-11-23T15:57:59.917

20

Inform 7

Inform 7 is a natural language based programming language for Interactive Fiction.

Factoid

Inform 7 is among the easiest languages to read, and was surreptitiously featured in why the lucky stiff's printer spool book. His code and the game it compiles to can be played online.

Length 3

X:Y

Inform 7 is a rules based language. The standard library defines many rulebooks and the player can define more. These rules are used for event handling and to create extensible procedures. Each rulebook can contain several rules, which consist of a rule preamble, and a body. The rule preamble is at a minimum the name of the rulebook, but it can also have many additional conditions.

In this example the rulebook preamble is the name of the rulebook X, and the body consists of a single phrase (function) Y. Inform 7 code is usually much more verbose than this, so these short examples will not be able to showcase the natural language aspects of the language ;).

Length 4

X YY

Each rulebook has a name and a basis: a variable type which is the main parameter for the rulebook. When you call a rulebook you can optionally call it for a particular value, which must match the type of the basis.

When a rulebook is called it goes through the rules in order and runs whichever rules have matching preambles. The preambles can specify that they want to run only for a particular subclass of the basis, only for values which meet a specific condition, or only for a single specific value. Rulebooks normally run all the rules with a matching preamble, but rules can stop it from continuing. The rules of a rulebook are automatically sorted in order from most to least specific so that if only one rule will be run, it will be the most specific one (though rules can be manually repositioned).

This example specifies a rule preamble for the rulebook X. YY could be either a subclass of the basis, an adjective phrase which checks whether the value matches some condition, or a particular object called YY.

Length 5

"[s]"

Here's the first example of real code! Text in Inform 7 can either be a simple literal string, or a dynamic text with substitutions which are processed at run time. Under the hood these texts are compiled to functions, but they are entirely interchangeable with simple literals.

Text substitutions can run essentially any other phrases/functions, and can be passed arguments too. Many come predefined in the base library. This example, the to say s phrase, will print an 's' if the last number printed was not 1. Similar substitutions can be used for entire sentences to output the correct grammatical inflections for a particular narration style (such as first person past tense or third person future tense), even allowing the narration style to be changed at run time.

curiousdannii

Posted 2015-01-19T12:36:59.320

Reputation: 657

20

Charcoal

Note: All snippets will be shown as if they were entered into a clean REPL.

39 bytes

Charcoal> UONNO_¶_OAKAαA№αOβHWψβ«A§α§⌕AαO‽βXA№αOβ

This is an animated example, so REPL output is not shown. It's also the submission for Make a Bubble-wrap simulator. It uses the AssignAtIndex (A§) command, which, when used with the Cells datatype (obtainable from Peek commands), changes the canvas.

30 bytes

Charcoal> ×⁶()↙↓¹⁰↖↖¹⁰↓↓²↘⁸M↑__↖←¤:↗¤≕Pi
()()()()()()
|\3.1415926|
|:\53589793|
\::\2384626|
 \::\433832|
  \::\79502|
   \::\8841|
    \::\971|
     \::\69|
      \::\3|
       \__\|

This is the (noncompeting) submission for Bake a Slice of Pi. It shows the (very unfinished) Wolfram Language support.

11 bytes

Charcoal> G↘↗↘↗↖↙↖↙⁵#  
    #       #    
   ###     ###   
  #####   #####  
 ####### ####### 
#################
 ####### ####### 
  #####   #####  
   ###     ###   
    #       #    

Polygon(:DownRight, :UpRight, :DownRight, :UpRight, :UpLeft, :DownLeft, :UpLeft, :DownLeft, 5, '#'). An example of a more complex polygon.

10 bytes

Charcoal> G↗↘←⁴*#M↓*
   #   
  *#*  
 #*#*# 
*#*#*#*
   *   

Polygon(:UpRight, :DownRight, :Left, 4, '*#'); Move(:Down); Print('*'). An example of multi-character fill in Polygon.

9 bytes

Charcoal> ┌┐‖M↓
┌┐
└┘

Print('┌┐');ReflectMirror(:Down). Another ASCII-art oriented builtin. Note that and count as three bytes each.

8 bytes

Charcoal> P+abcUB*
**c**
**b**
cbabc
**b**
**c**

Multiprint(:+, 'abc');SetBackground('*'). A very useful builtin in many situations.

7 bytes

Charcoal> B⁵¦⁵123
12312
1   3
3   1
2   2
13213

Box(5, 5, '123'). Demonstrates one of the many builtins with overloads for strings of length greater than 1.

6 bytes

Charcoal> aJ³¦³a
a    


    a

This isn't a very interesting one - Print('a');Jump(3, 3);Print('a'); but it demonstrates the separator ¦, useful when you have two numbers or two strings in a row.

5 bytes

Charcoal> G↗↘⁴_
   _   
  ___  
 _____ 
_______

An alternate syntax for Polygon - Polygon(:UpRight, :DownRight, 4, '_'), also demonstrating its autofill feature, when the cursor does not end up in the starting position.

4 bytes

Charcoal> G+⁵a
aaaaa
aaaaa
aaaaa
aaaaa
aaaaa

In verbose mode, this is Polygon(:+, 5, 'a'). Self-explanatory. Any identifier with a preceding : is attempted to be parsed as a direction.

3 bytes

Charcoal> WSι
Enter string: a
Enter string: sdf
Enter string: 

asdf

This is a while loop. In verbose mode this is equivalent to:

While(InputString()) {
    Print(i)
}

Loop variables are automatically chosen as the first free variable (greek letter starting at iota and wrapping around after omega). Truthiness is the same as Python truthiness.

2 bytes

Charcoal> ‽⁵
---

This demonstrates the syntax for operators, in this case a monadic Random operator. The syntax for integers can also be seen here, which is just a run of superscript digits. This returns an integer, which is implicitly printed as a line of that length using a character in \/-| depending on the direction of the line. In verbose mode this is Random(5).

1 byte

Charcoal> a
a

Expressions are implicitly printed if they are not preceded by a command character.

Factoid:

This language was designed specifically for ASCII-art challenges. The 95 printable ASCII characters aren't used as commands, so string literals are not delimited.

ASCII-only

Posted 2015-01-19T12:36:59.320

Reputation: 4 687

19

Z80 Machine Code

Factoid

The Z80 is probably the most famous CPU developed by Zilog. The company Zilog was started by dissatisfied Intel employees and their first CPU, the aforementioned Z80, was fully compatible with Intel's 8080, as well as having its own set of extended instructions. This was a big selling point as it meant that CP/M (a very popular OS in its day, designed for the 8080) could be run on a computer using a Z80 CPU with no changes to the software.

Length 1 snippet:

HEX Op code   Instruction name
-----------   ----------------
AF            XOR  A

Being an 8-bit processor, the Z80 has many 1-byte instructions of varying usefulness. On the surface this instruction would not seem to be particularly useful as what it does is calculate A XOR A, storing the result in A. However, since the result is always 0 and all other ways of setting A (the Z80's main register or Accumulator) to 0 are longer than 1 byte, that makes this an interesting and useful instruction! It also has the side effects of setting the Z Zero flag (to 1) and resetting the C Carry flag (to 0). If you don't mind losing the previous value in A this is also a shorter way of resetting C, although there are other non-destructive ways of resetting C in one byte. The more obvious way takes two bytes.

Length 2 snippet:

HEX Op code   Instruction name
-----------   ----------------
10 nn         DJNZ n

This is a combination instruction. Its full name is Decrement Jump Non Zero. It combines Decrement B (DEC B) with Jump Relative Non Zero (JR NZ, n) for a saving of one byte (very important for code golf!) It is also 3 T-states faster than using the two instructions separately, the actual time taken being dependant on the CPU's speed, typically 4 MHz. There is no other register that can be used instead of B and the only test for the jump is NZ, making this instruction unique because most other instructions have "siblings" such as the 75 different 8-bit load (LD) instructions.

If the value stored in B (an 8-bit register) is zero after being decremented, the program jumps n bytes, where n is a signed 8-bit integer. This means n can be anywhere from -128 to 127. The closest analogy with higher languages is the FOR loop where the code is executed B times. If B already contains 0 the first time DJNZ is executed, B gets decremented to 0xFF (-1 / +255) resulting in the loop executing another 255 times.

The simplest form is 10 FE # DJNZ -2 which jumps back two bytes (to itself) until B is zero. All this would do is make sure B is zero and delay the execution of the following code by an amount proportional to the initial value of B. Alternatively, the offset could be a positive amount, skipping the subsequent code the first B times. Interestingly, this instruction affects no flags, not even the Zero flag so extra size/time savings and/or more straightforward code can be obtained if it is wanted to pass the current value of Z to another part of the program.

Length 3 snippet:

HEX Op code   Instruction name
-----------   ----------------
DD 77 nn      LD   (IX+n), A

This introduces one of the two 16-bit index registers: IX. IX and its sister register, IY, are used to address offsets from memory locations without having to change the value of the register. A one byte, signed offset is set in the code (nn in the HEX code above). This is useful if you are reading or writing several non-continuous bytes from a single offset or multiple offsets in sequence. What this particular instruction does is LoaD the 8-bit value at the memory address (IX+n) with the value in the A register.

All instructions that use the IX register are prefixed with DD. This actually just changes the following instruction to use IX instead of HL, and then reads an additional byte after the Op code if it is in indirect addressing mode (indicated by the use of parentheses in the instruction name). The instruction 77 # LD (HL), A is the same instruction, but using HL instead of an indexing register.

IX is always intended to be used as a 16-bit index register, however, there are several unofficial, undocumented codes that allow using it as two 8-bits registers, HX and HL, just like the regular 8-bit registers H and L.

Length 4 snippet:

HEX Op code   Instruction name
-----------   ----------------
FD 36 nn xx   LD   (IY+n), x

There are very few 4-byte single instructions, all of which are similar in function and use one of the two index registers. This time I am using IY. All IY instructions are prefixed with FD. It is almost identical to the previous example but using a direct value instead of a register. It LoaDs the 8-bit value at the memory address (IY+n) with the value x in the last byte of the instruction. (Normally, this op-code would be written LD (IY+d), n but I am avoiding using d to prevent confusion with the hex digit D.)

Because of the way that DD and FD work, you can actually chain any number of DD and FD bytes together. Only the last one will take effect, wasting both memory and clock cycles. For example, FD FD DD AF will set the current instruction to use IY instead of HL, then IY again, then IX, then ignore them all and execute XOR A (see the length 1 snippet). As you can see, although it produces valid code, it is only useful to prefix instructions with DD or FD if they normally use the HL register (or the H or L registers if you are using undocumented instructions). The CPU automatically resets to using the HL register instead of an index register after each instruction, whether or not an index register actually ended up getting used.

Length 5 snippet:

HEX Op code   Instruction name
-----------   ----------------
AF            XOR  A
80            ADD  A, B
05            DEC  B
20 FC         JR   NZ, -4

There are no single instructions longer than 4 bytes (except for the aforementioned wasteful instructions) so now I need to write mini programs! This snippet calculates the nth triangular number (mod 256 since these registers are 8-bit) from 1 to 256. On entry the B register contains n. On exit the A register contains the result, B contains 0, the Z flag is set, the other flags are corrupted (not guaranteed to stay unchanged, nor to hold useful values, although the value of each flag will be the same after every time this snippet is run; the values are not random and can be predetermined) and all other registers are preserved (unchanged). How can it calculate 256 since the largest 8-bit unsigned value is 255 and why doesn't it calculate 0?

It sets the A register to 0 (see the length 1 snippet), ADDs B to A, storing the result in A then DECrements B. If the value of B is 0 after being decremented, then the Z flag is set. The last instruction Jumps Relative to the current position if the Z flag is not set (Non-Zero), i.e. if B is not 0. FC is treated as a signed value, so it jumps by -4 bytes from the end of the JR NZ, n instruction if the condition is met. So, if B is already 0 upon entry, decrementing it will overflow and set it to 255, causing the snippet to loop 256 times. The largest value it can calculate without overflowing is Tri(22)=253. The result of the next value, Tri(23) is 20 because 276 doesn't fit in an 8-bit number.

CJ Dennis

Posted 2015-01-19T12:36:59.320

Reputation: 4 104

I just started page 4 of this question! – CJ Dennis – 2015-05-18T06:39:54.680

if it is compatible to the 8080, how is the Z80 machine code different from 8080 machine code? – Paŭlo Ebermann – 2015-09-07T22:36:03.750

@PaŭloEbermann The Z80 extends four unused op-codes. All 8080 op-codes are single byte but the Z80 has multi-byte op-codes starting with CB, DD, ED & FD. A lot of these are used to address registers that don't exist in the 8080. – CJ Dennis – 2015-09-14T13:33:51.030

19

Desmos

(View them here!)

17-vote

\frac{d}{dx}x^4+x

Derivatives!

16-vote

\prod _{n=1}^x n

This is the factorial function, using a product instead of x!.

15-vote

\left[xx\right]

FINALLY! We have a bracketted equation! This is a single-element array containing the equation x*x.

14-vote

\frac{-3}{x^2}

This is a fraction with -3 on top and x^2 on top.

13-vote

-x^2/\cos x^2

Where are your parents now! This creates a sick-looking equation.

12-vote

x^x+y^y=xxy

This equation shows all possible values for which the above holds true. This tells us that Desmos can show an extreme amount of detail, and is not your average calculator.

11-vote

ex^2-x=\pi 

(note the trailing space) This solves for the variable x, that is, x = -0.90673034 or 1.2746098.

10-vote

r=.5\theta 

(There is a trailing space, mandatory as per this meta post) This creates a lovely parametric equation i.e. tight-ish spiral.

9-vote

3x\ge 4y^2

Desmos supports inequalities of nonlinear quality! This produces the inequality 3x ≥ 4y2 and graphs it.

8-vote

\theta _2

This shows that Desmos supports the explicit \theta variable, which prints like this: θ. The _2 is a subscript, so the full result would look like this: θ2. This formula also shows a quirk of how bytes are counted in Desmos: though the space could be removed and still have the same copy-and-paste result, the result that is copied from Desmos forms the byte count. This will also explain why no results with parentheses, etc., have thus been posted; since copying a pair of parentheses would result in \left(\right), a 13-byte expression, these will not be posted until around ~14+ votes.

7-vote

\cos bx

When Desmos encounters an undefined variable, Desmos creates a small popup:

When you click on that button, the following formula will be inserted in the slot after the original function:

Pressing the play button will allow you to "phase" through values of b, seeing the display update. Check the link above to observe this behaviour. This also shows Desmos's support for implicit parenthesis in a trigonometric function, so long as all of its inputs are "attached" with multiplication or division operators. (The latter only happens when directly copy+pasting the code into the editor.)

6-vote

\sin x

Desmos supports trigonometric functions, defined like that in (La)TeX. This draws a graph, as the variable x is taken to mean an equation variable.

5-vote

x=y^2

A function of y… how cool is that!? Something your ol' TI-84 can't do…

4-vote

2x^3

This is an implicit definition of an equation (implied is f(x)). This draws the graph of aforementioned function. (Also shows that Desmos will interpret a number next to a variable to mean multiplication, that is, coefficient multiplication.)

3-vote

a=5

Desmos supports the definition of variables.

2-vote

.3

Desmos supports decimal numbers without the leading zero.

1-vote (thanks!)

7

Numeric literal. Comment: Up until about 5-7 votes, you'll be getting interesting numbers.

0-vote

Desmos is an online graphing tool to help those in the mathematical field to visualize problems like trigonometry, basic derivation, and even 3D graphs!

Conor O'Brien

Posted 2015-01-19T12:36:59.320

Reputation: 36 228

1Judging from the snippets so far, I don't know what you can do with less than about twenty characters, but impress me. – lirtosiast – 2015-09-29T02:03:55.183

@ThomasKwa Thanks ^_^ I will. – Conor O'Brien – 2015-09-29T02:13:35.270

1Link for the interested – DanTheMan – 2015-09-29T03:07:44.880

19

Seriously/Actually

Length 16 snippet

????????????????

Like the length 10 snippet originally was, this snippet is hidden until somebody finds the easter egg.

In this commit, I introduced an easter egg. If you input the correct 16-byte code as an Actually program, something special will happen!

Length 15 snippet

[1,2,3,4,5];♀ⁿσ

Try it online!

This snippet showcases two new features of Actually:

  • The binary map operator : it works like , but maps a binary function over the top two stack elements, instead of mapping a unary function over the top element.
  • The cumulative sum function σ: it takes a list as input, and outputs a list where each element is the sum of the first n elements of the input list.

The program outputs the cumulative sums of [x**x for x in [1,2,3,4,5]]. The equivalent Python code would be [1**1,1**1+2**2,1**1+2**2+3**3,1**1+2**2+3**3+4**4,1**1+2**2+3**3+4**4+5**5].

Length 14 snippet

1WX╚;;S=YWX♂.X

This snippet sorts the input list using bogosort and prints out each value in ascending order, separated by newlines.

Cool things in this snippet:

  • Implicit input: because there are no input commands (,, , , or ) in the code, Actually reads all input, parses it, and pushes it before beginning evaluation of the code.
  • The command: it's a shortcut for the map (M) command. It takes the next command (. in the above snippet) and maps it over the list on top of the stack. ♂. is functionally equivalent to the following (and 2 bytes shorter!):
`.`M

Length 13 snippet

:12345678;;+▼

This snippet shows off a lot of new things. In no particular order:

  • :12345678: improved numeric parsing. Rather than needing to be wrapped in :s, numerics merely need to be prefixed with one, and are parsed as the longest string following the : consisting only of characters in 0123456789+-.ij.
  • : new function (gcd reduce). In this form, it pops two integer values off the top of the stack, and pushes them divided by their gcd.
  • : dingbats for characters 0x01 - 0x1F. No more typing those pesky invisible or formatting-ruining ASCII control codes.

Length 12 snippet

[[1,2],[3,4]

Now that Seriously v2.0 (codename Actually) has been released, it's time to start showing off some nifty features I've added. This snippet shows off nested lists - something that Seriously was lacking because I didn't take the time to write a good parser when I created it. This pushes [[1, 2], [3, 4]] to the stack.

But wait, it's missing the ending bracket! Actually, it isn't. It's implied at EOF. However, the inner list(s) still need their ending brackets, even if the ending brackets are at the end of the source code. This may be changed soon.

Length 11 snippet

Note: this is defunct as of now, due to the Heroku site being disabled. No worries though, a similar easter egg will be added into the actual Python interpreter soon.

↑↑↓↓←→←→ba

A newline at the end makes this 11. This is the infamous Konami code - "up up down down left right left right b a" (pressing enter to confirm the code, like start in Contra). Entering this in the online interpreter, using the arrow keys for the directional inputs, will result in a fun little easter egg - the second easter egg I added.

Length 10 snippet

??????????

I added two easter eggs to the Seriously interpreter recently. The first one (from this commit) involves doing something special when your code starts with a certain 10 characters. However, I don't want to spoil the secret, so until somebody figures it out, the above code will just be 10 question marks (which is not the secret).

Since I've revealed the original secret in chat, I might as well reveal it here too.

In v1, back before I removed the easter egg, if your code started with ^^vv<><>ba, the rest of the code would get exec'd (run as Python code).

The ? character will eventually be used as a prefix for some two-byte commands, once the single-byte command table fills up. In addition, once I get it working, ?? will be a comment delimiter.

Update: This secret was causing the interpreter to misbehave, so it has been removed for now. It will come back later, once I can make sure it doesn't break things again.

Length 7 snippet

,▓r`P`M

This snippet prints a list of the primes that are less than or equal to the input value.

 ,    push input (indented one extra space here so that the below character doesn't hide it)
▓    pop a: push pi(a) (# of primes less than or equal to a)
r    pop a: push range(0, a) ([0,...,a-1])
`P`  define a function that executes P (pop a: push the ath zero-indexed prime)
M    pop a function f and a list l, apply f to each element of l

Seriously is seriously powerful and terse when it comes to math. I refuse to apologize for the terrible pun.

Length 6 snippet

╦ï*╠^φ

This snippet showcases the mathematical constant builtins:

pushes π.

ï pushes i, the imaginary unit.

* multiplies the top two values.

pushes e.

^ pops a and b, and pushes pow(a,b).

φ pushes φ, the golden ratio.

Output:

1.61803398875
(-1+1.22464679915e-16j)

This snippet demonstrates Euler's Identity, one of the most important identities in complex analysis: e^(i*π) = -1. The output value isn't quite -1 due to floating-point precision issues and rounding errors, but it's very close. It also outputs φ because I needed a 6th character and I wanted to show off all of the math constants.

Length 5 snippet

:1+2j

Complex number support! I worked a long time on getting this functioning, because Python 2 (the language Seriously is implemented in) does annoying things involving complex numbers.

: is the numeric delimiter - everything between it and the next : (or, in this case, EOF - hooray, more implied delimiters) is interpreted as a numeric value and pushed. If it can't be interpreted as a numeric value, 0 is pushed instead, following the tenet of No Errors.

Length 4 snippet

asdf

a: invert the stack

s: pop a: push sgn(a)

d: pop [a]: dequeue a value b from [a], push [a],b

f: pop a: push the index of a in the Fibonacci sequence, or -1 if a is not a Fibonacci number.

Pretty simple, right? Wait... There's nothing on the stack! How is this program supposed to work?

In Seriously, one of the fundamental design tenets was that there are no errors. If a command does not get an appropriate value from the stack, it does not throw an error. Instead, it restores the stack and quietly exits. All of these commands are NOPs when the stack is empty.

Length 3 snippet

,,+

This reads in 2 values and adds them (for whatever adding means for the two values). If you pass in two ints, like 5 and 3, the result will be 8. If you input two strings like "foo" and "bar", they are concatenated to form "barfoo" (reversed because they are appended in the order they appear on the stack). If you input two lists, the result will be appending the second to the first: [1,2,3][3,4,5]+ -> [3,4,5,1,2,3]. Adding functions results in their code being appended. Whatever the result, it will be printed to STDOUT.

...wait, why is it printed to STDOUT? There's no . in that snippet! Or is there? When a Seriously program terminates, each value on the stack is popped and printed - there's no need for an explicit . or ü at the end of a program. This is just another feature that saves those ever-precious bytes.

Length 2 snippet

1W

This is an infinite loop. 1 pushes the integer 1 onto the stack, and W is a loop delimiter - the code inside the loop (which is nothing) executes while the value on top of the stack (which is peeked, not popped) is a truthy value (not 0, '', [], or an empty function). This snippet shows off one of my favorite features in Seriously: like TI-BASIC, closing delimiters are not needed at the end of programs; they are implicitly present at EOF.

Length 1 snippet

H

This prints Hello, World! to STDOUT if the stack is empty.

Factoid

Seriously got its name from this challenge.

Mego

Posted 2015-01-19T12:36:59.320

Reputation: 32 998

Is the secret easter egg code: Seriously?? Just a random guess. – DJgamer98 – 2015-11-20T10:29:58.123

@DJgamer98 Try it and find out :) – Mego – 2015-11-20T22:44:41.243

-1 interpreter doesnt exist – CalculatorFeline – 2016-04-07T00:10:28.487

@CatsAreFluffy Oh yeah I need to add the Easter egg into the language proper since I killed off the heroku app. Watch this space for more stuff once I finish the first release of v2. – Mego – 2016-04-07T02:38:40.977

@CatsAreFluffy What do you mean an interpreter doesn't exist? http://seriously.tryitonline.net/

– mbomb007 – 2016-04-20T16:00:14.447

@mbomb007 I mean the old Heroku online interpreter is dead. – Mego – 2016-04-20T19:33:48.870

19

beeswax

Factoid:

beeswax is a self-modifying 2D esoteric programming language created by Manuel Lohmann, based on a 2-dimensional hexagonal grid. Every cell in a beeswax program (the honeycomb) has 6 neighbors.

  2 — 1
 / \ / \
3 — β — 0
 \ / \ /
  4 — 5

Actual layout:

21
3β0
 45

Instruction pointers (called bees) travel around on the honeycomb. Bees can pick up values from any location on the honeycomb, or drop values on it, potentially changing its size and content. Every bee carries a stack (local stack/lstack), with a fixed length of 3. Bees can interact with a global stack (gstack) of unlimited length that’s accessible by all bees. The gstack only allows basic stack operations like rotating up, down (similar to how Piet handles the stack) and pushing and popping values on or off the stack. All arithmetic or bitwise manipulation of data has to be done by bees. All values in beeswax are unsigned 64-bit integers.

GitHub repository to a beeswax interpreter written in Julia


All snippets in reverse order:

Length 15 snippet (introducing the print toggle switch)

The good old plain “Hello, World!”

*`Hello, World!

The backtick character ` is a toggle switch to print every character encountered after the switch to STDOUT until a second backtick toggles the output off again or until the bee leaves the honeycomb or the program ends, whichever occurs first.

Length 14 snippet

in the works

Length 13 snippet

in the works

Length 12 snippet II

p{N<P{*
>~+d

Another 12 bytes long example. This calculates and outputs the fibonacci sequence, part of my solution to the Fibonacci function or sequence challenge.

Finally a program doing something more useful again.

Explanation:

          lstack     output
      *   [0 0 0]•            create bee
     {                 0      output lstack 1st as integer to STDOUT
    P     [0 0 1]•            increment lstack 1st
   <                      (1) redirect to left
  N                   \n      output newline to STDOUT
 {                     1      output lstack 1st as integer to STDOUT
p                             redirect to lower left
>~        [0 1 0]•            redirect to right, flip lstack 1st and 2nd
  +d      [0 1 1]•            lstack 1st=1st+2nd, redirect to upper right
   <                          redirect to left, loop back to (1)
  N                   \n      utput newline to STDOUT
 {                     1
p
>~        [0 1 1]•
  +d      [0 1 2]•
   <
  N                   \n
 {                     2
p
>~+d      [0 2 3]•
  N<                  \n
p{                     3
>~+d      [0 3 5]•
  N<                  \n
p{                     5
...
...

This outputs the fibonacci sequence, but only up to the 93rd element, after which 64bit-wraparound causes the sequence to produce wrong values:

       ...
4660046610375530309
7540113804746346429
12200160415121876738   ← 93rd Fibonacci number, last correct value
1293530146158671551    ← 1st. case of 64-bit overflow/wraparound
13493690561280548289
       ...

Implementing a longer word length is possible, of course. Maybe I can implement such a fibonacci sequence program in one of the next examples.

Length 12 snippet

This is my contribution to the Code that executes only once challenge. You have to save this program in a file named !. This program does not add any new fancy ideas—it is just a slightly modified realization of the idea shown in snippet length 10.

_8F+++P]f1Fw

Explanation

                  lstack                        gstack
_8F+++P        [0x08,0x08,0x21]•
       ]       [0x08,0x08,0x2100000000000000]•                        rotate bits of lstack 1st by lstack 2nd steps to the right
        f1     [0x08,0x08,0x01]•               [0x2100000000000000]•  push lstack 1st on gstack, set lstack 1st to 1
          Fw   [0x01,0x01,0x01]•                                      write file named "!" (Char(0x21)) with content 0x00 (1 byte).

So, during execution the program overwrites its own file, so it can’t be executed again.

Length 11 snippet (clear screen using ANSI escape sequence)

_3F..}`[2J`

This is my beeswax example for the task Terminal control—Clear the sreen on rosettacode, which can be found here.

• marks top of stack
             lstack
_            [0 0 0]•    create bee
 3           [0 0 3]•    lstack 1st=1
  F          [3 3 3]•    all lstack = 1st
   .         [3 3 9]•    1st=1st*2nd
    .        [3 3 27]•   1st=1st*2nd
     }                   output lstack 1st as char to STDOUT
      `[2J`              output `[2J` to STDOUT

This program uses the ANSI escape sequence ESC[2J, as shown here. 27 is the ASCII code for the control character ESC, [2J is the rest of the ANSI escape sequence to clear the screen.

Length 10 snippet (introducing the file write instruction)

_Z~8~]f1Fw

This program writes a file named “Z”, containing one byte of information: 0

             lstack               gstack
_           [0,0,0]•                                 create bee
 Z          [0,0,90]•                                pick up value from relative address lstack(1st,2nd), see length 7 snippet.
  ~         [0,90,0]•                                flip lstack 1st,2nd
   8        [0,90,8]•                                lstack 1st=8
    ~       [0,8,90]•                                flip lstack 1st,2nd
     ]      [0,8,6485183463413514240]•               rotate bits of lstack 1st by lstack 2nd steps to the right.
      f     [0,8,6485..4240]• [6485183463413514240]• push lstack 1st on gstack
       1    [0,8,1]•                                 lstack 1st=1
        F   [1,1,1]•                                 set all lstack to 1st value
         w                                           write file [-,filebytes,namebytes]•

The “magic” becomes obvious if we look at the hex values of the stack contents:

                                   lstack                                     gstack

_           [0x0000000000000000,0x0000000000000000,0x0000000000000000]•
 Z          [0x0000000000000000,0x0000000000000000,0x000000000000005a]•
  ~         [0x0000000000000000,0x000000000000005a,0x0000000000000000]•
   8        [0x0000000000000000,0x000000000000005a,0x0000000000000008]•
    ~       [0x0000000000000000,0x0000000000000008,0x000000000000005a]•
     ]      [0x0000000000000000,0x0000000000000008,0x5a00000000000000]•
      f     [0x0000000000000000,0x0000000000000008,0x5a00000000000000]• [0x5a00000000000000]•
       1    [0x0000000000000000,0x0000000000000008,0x0000000000000001]•
        F   [0x0000000000000001,0x0000000000000001,0x0000000000000001]•                                 
         w

At instruction w lstack is [1,1,1]•. This means, lstack 1st bytes (1 byte) of gstack are used for the file name, and lstack 2nd bytes (1 byte) are used for the file content. The first byte of gstack is 0x5a, or 90 in decimal. This is the ASCII code for the character Z. The next byte is 0x00,which is the file content. So, this program creates a file Z with the content 0x00.

Length 9 snippet in the works...

Length 8 snippet II (truth machine, introducing all conditional operators)

My solution to the challenge Implement a Truth Machine. My full explanation can be found there.

 _T> "{'j

It’s not a real showcase without a truth machine, right? ;) This example also showcases two different conditional jump instructions that are working hand in hand in their functionality.

If lstack is [0,0,0]• (the user entered 0) then the bee only visits the instructions:

_T> "{'

and jumps outside the honeycomb, which terminates the program after printing out one 0 to STDOUT.

If lstack is [0,0,1]• (the user enters 1) then the case gets more interesting:

_T> " 'j'{"> " 'j'{"> " 'j'{">....

which lets the program output an infinite stream of 1s to STDOUT. Instruction j reflects the direction of the IP horizontally (see the list at the length 4 snippet) to run the check over and over again.

Beeswax has 4 conditional and one unconditional “skip next” instructions:

' skip next instruction if lstack 1st value = 0.

" skip next instruction if lstack 1st value > 0.

K skip next instruction if lstack 1st value = 2nd value.

L skip next instruction if lstack 1st value > 2nd value.

Q skip next instruction unconditionally.

Length 8 snippet (introducing absolute addressing)

_4F(@0@D

Explanation:

          lstack
_         [0,0,0]•        create bee
 4        [0,0,4]•        lstack 1st=4
  F       [4,4,4]•        lstack=lstack 1st
   (      [4,4,64]•       1st=1st<<2nd (arithmetic shift left)
    @     [64,4,4]•       flip lstack 1st/3rd
     0    [64,4,0]•       lstack 1st=0
      @   [0,4,64]•       flip back
       D                  drop lstack 1st at row,column = lstack 2nd,3rd

Result:

 _4F(@0@D


@

The 3 instructions D(drop value at cell), G(get value from cell) and J(jump to cell) use absolute addressing. Beeswax programs use 1-indexed coordinates, the y coordinate pointing “downwards”, with the origin at the upper left corner of the honeycomb. Instruction D has the ability to change the size of the honeycomb by dropping values outside the current honeycomb area. Growth in positive direction (down and right) is only limited by the UInt64 number range, growth in negative direction is only possible if values get dropped to the coordinate (0,n), (n,0) or (0,0). The example above drops the value 64 (ASCII for @) at (row,column)=(4,0) Column 0 is the (imaginary) column right at the left border of the honeycomb. If the honeycomb grows in negative direction, then the origin of the new honeycomb gets reset to the new upper left corner. That means, in the example above, the new origin (1,1) changes to the coordinate left of the _. Negative growth is only possible in steps of 1 because unlike the relative addressing instructions, D does not recognize 2’s complements as negative numbers.

A little word of advice: Don’t try to drop values at too high addresses because you’ll run out of memory very quickly. An area of roughly 11,600x11,600 cells already needs at least 1 GB of memory (if the cells only contain 8-bit values and no multibyte characters).

length 7 snippet (introducing relative addressing)

_T";@Z}

The program above is not really useful, but it demonstrates how the code manipulation instructions that address cells locally work in beeswax. There are two of these instructions that address cells locally: Y and Z. Instruction Y drops values to a cell that’s addressed relative to the position of Y in the program. Instruction Z picks up a value from a cell that’s addressed relative to the position of the Z instruction. As all values in beeswax are unsigned 64 bit integers, there is a problem. You can’t address any cells at relative addresses lower than (row,column)=(0,0). But bees aren’t stupid, so they figured out how to solve that problem by using the two’s complement of the addresses for the cells in question, meaning cells located at the left or below (the coordinate system of the honeycomb is flipped upside down). The two’s complement of a 64 bit integer n is simply 2^64-n.

The addressing works identical for instruction Y.

At instruction Z in the example, relative address

(0,0) is the cell of the instruction itself, returning the value 90, the ASCII value of Z.

(0,1) returns 125, the ASCII value of }

(0,2) returns 0, the default return value if the relative address is outside the honeycomb.

(0,-1) becomes (0,18446744073709551615) and returns 64, the ASCII value for @, and so on.

Z picks up values at the relative address lstack[column,row,-]• and puts the value that’s found at that address on top of the lstack.

Program flow:

_                            create bee
 T                           read in integer from STDIN (enter column of character to be read)
  "                          skip next instruction if lstack 1st>0
   ;                         terminate program (if user entered 0)
    @                        flip lstack 1st and 3rd values
     Z                       pick up value from cell at lstack[column,row,-]3
      }                      output lstack 1st as char to STDOUT

Examples:

julia> beeswax("snippet7.bswx")
i0

Program finished!

julia> beeswax("snippet7.bswx")
i1
}
Program finished!

julia> beeswax("snippet7.bswx")
i2
�
Program finished!

julia> beeswax("snippet7.bswx")
i18446744073709551615
@
Program finished!

julia> beeswax("snippet7.bswx")
i18446744073709551614
;
Program finished!

julia> beeswax("snippet7.bswx")
i18446744073709551613
"
Program finished!

Length 6 snippet (Introducing lstack I/O)

*T~T+{

Introducing new instructions: T and ~

Explanation: ( marks top of stack)

        lstack

*T      [0,0,a]•     Create bee. Get integer from STDIN, store as lstack 1st value.
  ~     [0,a,0]•     Flip lstack 1st and 2nd values.
   T    [0,a,b]•     Get integer from STDIN, store as lstack 1st value.
    +   [0,a,a+b]•   lstack 1st = lstack 1st + lstack 2nd.
     {  [0,a,a+b]•   Output lstack 1st to STDOUT

This program adds two positive integers given by the user.

There are 4 I/O operators that interact only with the lstack:

T Get integer value from STDIN, store as lstack top value.

, Get character from STDIN, store its value as lstack top value.

{ Output lstack top value as integer to STDOUT.

} Output lstack top value as Character to STDOUT.

Just for convenience, during program execution T and , give different output for the input request, so the user knows what is wanted by the program.

T outputs an i to remind the user that an integer is requested. , outputs a c to remind the user that a character is requested.

The program above looks like this during execution:

julia> beeswax("A+B.bswx")
i3
i5
8
Program finished!

Length 5 snippet

_9FB{

This program ouputs 387420489 to STDOUT, which is the result of 9^9.

Explanation ( marks top of stack):

step          lstack

_9          [0,0,9]•         Create bee, set lstack top value to 9.
  F         [9,9,9]•         Set all lstack values to the first value. 
   B        [9,9,387420489]• lstack top = top^2nd.
    {       [9,9,387420489]• output lstack top to STDOUT.

In beeswax, the numbers 0...9 set the top of lstack to the appropriate integer value.

F sets all lstack values equal to the topmost value. The other operator setting all lstack values to the same value is z (not used here), which sets all lstack values to 0.

This is the first example that uses an arithmetic operator, B, which raises lstack 1st to the power of lstack 2nd value.

Length 4 snippet (Introducing redirection and reflection instructions)

>_{j

This program outputs an infinite string of zeros.

time      state  output

tick 0:    >_{j
tick 1:    >α{j         _ creates two bees:
                        the first (α) moving right.
                        the second (β) moving left.
tick 2:    β_αj    0    α executes { and outputs its topmost lstack value to STDOUT.
                        β gets redirected to move to the right.
tick 3:    >β{α         α arrives at j, gets mirrored back to the left.
                        β moves to the right, ignoring the _ instruction.
tick 4:    >_αj    00   α and β arrive at the { instruction,
                        both output their top lstack value to SDTOUT, first α, then β.
tick 5:    >α{β         α moves on, β gets reflected.
tick 6:    α_βj    0    α gets redirected to the right
                        β outputs top lstack value to STDOUT.
tick 7:    >α{j         α and β arrive at _ and move on.
                        This state is identical to the state at tick 1.
tick 8:    β_αj    0    Identical to state at tick 2.
  .          .     .                   .
  .          .     .                   .
  .          .     .                   .

beeswax has 6 direct redirection instructions: < b d > q p, redirecting to the left, upper left, upper right, right, lower right and lower left, respectively, as shown in the diagram below (α showing the bee, the numbers the direction):

  b   d
   2 1 
< 3 α 0 >
   4 5 
  p   q

Indirect redirections

Here is a table with all mirroring instructions and their resulting reflected direction.

a and x turn the direction one step clockwise and counterclockwise.

O reflects all directions in the opposite direction.

s,t,u reflect along the main axes \(2-5),/(1-4),(0-3).

j,k,l reflect along the half axes |(between 1-4 and 2-5),/(between 0-3 and 1-4),\(between 0-3 and 2-5).

╔════════════════════════════════════╗
║incoming  a  x  s  t  u  j  k  l  O ║
╠════════════════════════════════════╣
║   0      1  5  4  2  0  3  1  5  3 ║
║   1      2  0  3  1  5  2  0  4  2 ║
║   2      3  1  2  0  4  1  5  3  1 ║
║   3      4  2  1  5  3  0  4  2  0 ║
║   4      5  3  0  4  2  5  3  1  5 ║
║   5      0  4  5  3  1  4  2  0  4 ║
╚════════════════════════════════════╝

Length 3 snippet

Cat program.

_,}

Introducing two new instructions:

, reads a character from STDIN and pushes its value on top of lstack.

} returns lstack top value as character to STDOUT.

Length 2 snippet

*{

Introducing the { instruction, which outputs the integer value of the top of the lstack to STDOUT. The lstacks of all created IPs/bees are initialized to [0,0,0] at program start, so this program just ouputs 0 to STDOUT.

Length 1 snippet

The shortest valid beeswax program contains at least 1 of 4 instructions to create bees at the start of the program.

A program only containing one of these instructions does not accomplish anything; the bees get destroyed as soon as they leave the honeycomb. A program that loses all its bees during runtime gets automatically terminated.

  • * creates 6 bees, each moving in one of the 6 possible directions in the following order of creation: 0, 1, 2, 3, 4, 5.

  • \ creates 2 bees in the following order: first bee moving to the upper left (dir. 2), second bee moving to the lower right (dir. 5).

  • / creates 2 bees in the following order: first bee moving to the upper right (dir. 1), second bee moving to the lower left (dir. 4).

  • _ creates 2 bees in the following order: first bee moving to the right(dir. 0), second bee moving to the left (dir. 3).

During program initialization the honeycomb is scanned for these 4 instructions column by column, starting in the upper left corner and ending in the lower right corner of the honeycomb.

A beeswax program may contain an arbitrary amount of these 4 instructions. All created bees are pushed on an IP stack, so the first bee executing code after initialization is the last bee that got pushed onto the IP stack. After initialization, the creation instructions have no effect on program execution anymore and get ignored by the bees if they encounter these instructions.


Length 0 snippet

Invalid program. Beeswax demands at least one instruction for IP creation, no matter how large the program is. The interpreter stops with an error message.

julia> beeswax("invalid program.bswx")
ERROR: No starting point found. Not a valid beeswax program.

M L

Posted 2015-01-19T12:36:59.320

Reputation: 2 865

2http://meta.codegolf.stackexchange.com/q/6918/8478 – Martin Ender – 2015-12-26T13:25:39.937

18

Perl

Factoid
Perl is a general-purpose, dynamic programming language. It was created by Larry Wall in 1987 and is still widely used today. Perl is not an acronym, but there are a couple of backronyms in place, such as "Pathologically Eclectic Rubbish Lister" "Practical Extraction and Report Language".
Snippet Length 1
;
In Perl, semicolons mark the end of a line. Because empty lines are ignored, this program simply exits without doing anything.
Snippet Length 2
1;
1 is a true value in Perl. In Perl modules, the code has to end with a true value, usually this (or sometimes something rather silly.)
Snippet Length 3
&a;
You're probably wondering: "What's that funky symbol doing there?" Well, in Perl, the & symbol marks the beginning of a subroutine (also known as a function). This executes the subroutine a and quits.
Snippet Length 4
1+1;
Any positive non-zero number is true in Perl, as well as almost any non-empty string. ('0' is false.) Since 1 + 1 = 2, and 2 is a positive number, this works just like the 1; snippet.
Length 5
$_=3;
This assigns a scalar variable in Perl. See that $? That's what makes it a scalar. This assigns $_ with the value 3.
Length 6
print;
There's something special about $_: it's Perl's default variable. Most times, if an argument is not given, it falls back to $_. This prints 3, assuming you set a variable like in the length 5 snippet. Length 7
s/b/B/g
What is THAT? Did I just take letters and add slashes? No, this is the substitution operator. What it does it is takes a little b and replaces it with a big B. The /g is for global, which tells it to do this for all matches. Of course, it's doing this on $_, Perl's default variable, but I'll show you how to do it properly later.
Length 8
@l=(3,4)
This defines an array with the items 3 and 4 in it. An @ makes it an array, just like $ makes it a scalar. Note that @_ is not Perl's default array.
Length 9
if(2>1){}
The if conditional works as you would expect it to in other languages. It checks if the statement inside the parentheses is true, and if it is, executes the code in the brackets (in this case, none.) Note that the brackets do not have to end with a semicolon.
Length 10
$o=`cat A`
In Perl, backticks can be used to get the output of a command. Here, it gets the contents of the file "A" (from the cat command.)

ASCIIThenANSI

Posted 2015-01-19T12:36:59.320

Reputation: 1 935

Length 8 is incorrect. It gives you an array with one array ref in it. – skibrianski – 2015-09-07T23:55:28.087

@skibrianski Thanks for pointing that out, it's fixed now. – ASCIIThenANSI – 2015-09-08T17:23:08.857

18

Fishing

Fishing is a 2-D programming language created by OriginalOldMan in 2013.

Factoid

This language is based off of "fish" that a "fisherman" catches as he walks along a "dock." Fishing implements a memory tape similar to that of Brainfuck.

Note: Since Fishing is very byte-inefficient and that programs with odd byte count are impossible, the length refers to the number of characters used to define the dock. The dock begins after the initial direction walking, direction casting, and casting length of 1 have been set.

Dock Length 0

v+

This sets the fisherman to cast his line down by 1 space. The direction the fisherman casts is determined by v, >, <, and ^. The length of the line being casted must be a positive integer to work. It is controlled by + and -. By default, the fisherman begins walking east. The commands for the direction the fisherman walks are [ to go east, ] to go west, | to go north, and _ to go south.

Dock Length 1

>+CI

This sets the first cell on the tape equal to the user input. Note that the fisherman is casting to the east.

Dock Length 2

v+CC
  IN

This is cat. The user input will be printed with a trailing newline.

Dock Length 3

v+CCC
  `A`

This assigns the string A to the first cell on the tape.

When the fisherman catches a tick, the string between the ticks is assigned to the first cell (and can be printed with P or N).

Dock Length 4

>+_
  C`
  C3
  C`
  Cn

Look! Our first example of the fisherman not walking east for the entire program. Like in the snippet with dock length 2, the fisherman will cast west. However, he will also be walking south. Here, the command to walk south must occur after the fisherman receives the information that he is casting to the right by 1, or there will be an error.

In order to have a manipulatable number on the tape, the number must be entered as a string and later be converted into a decimal with n.

Dock Length 5

v+CCCCC
  `ab`r

The string ab is put on the tape, and r is used to reverse it. Note that r cannot reverse a number if the command n has been used on the number. Thus, r will work for the fish `12`r but not for `12`nr.

After the above program, the tape contains the string ba.

Dock Length 6

    a `N
v+C^CDCC
  `

Here, we see a couple modifications to the dock itself. The direction of casting is changed from south to north by ^. We also see D for the first time. D does not have any function but to keep the fisherman walking on the dock. The fisherman does not cast or change direction. The only function of D is for space.

The above program prints a with a trailing newline.

Dock Length 7

v+CCCCCCC
  `4`{`1`

Fishing works through a series of cells on a tape. It's about time we see implementation of multiple cells. The above code assigns 4 to the first cell, moves to the right by one cell with { (moving to the left is done with }), and assigns 1 to the second cell.

Dock Length 8

v+CCCCCCCC
  `185`nSN

We should recognize n and N from before, but S is new. S squares the value in the current cell. The above program will print 34225, which is equal to 185^2.

Dock Length 9

v+CCCCCCCCC
  `2015`l{N

l is an interesting fish. It finds the length of the current cell and adds it to the end of the tape. The above code will print the length of the string 2015, which is 4.

Dock Length 10

v+CCC+CCC+CC
`p`ersonally
unliquidated
disjunction`
liver`morium

One of the cool things about Fishing is that it is really easy to obfuscate messages, such as above or in this obfuscated Hello, World!. The fisherman does not need to catch all of the fish in the program, as seen above. Any characters in the pond that are not caught are simply ignored.

The above program puts eridan on the tape. The er in personally, the ida in unliquidated, and the n in disjunction are used. Another grid that would put eridan on the tape is here.

v+CCC+CCC+CC
..`er.......
......ida...
..........n`

Dock Length 12

v+CCCCCCCCCCCC
  `9`n{`8`n}aP

We can finally have non-arbitrary interactions with other cells on the tape without the value of the second cell depending on the value of the first. We achieve this with a, which adds the value of the cell to the right on the tape to the current cell on the tape. The above will set the value of the first cell to the integer 9, set the value of the second cell to the integer 8, then replace the first cell with 17, and print it.

Dock Length 16

v+CCCCCCCCCCCCCCCC
  `Hello, World!`P

There it is: Hello, World! This should be the shortest version there is.


Unfortunately, since Fishing isn't that high-tech of a language, my answer will stop here. Thank you all very much for upvoting!

Arcturus

Posted 2015-01-19T12:36:59.320

Reputation: 6 537

2Heh, of course you'd do a fish-themed language, – Deusovi – 2015-10-27T18:28:25.150

@Deusovi I'm going to be perfectly honest here - I never realized the irony of that. – Arcturus – 2015-10-27T18:31:43.587

My goal for this answer is just to get to 16 so I can post Hello, World! – Arcturus – 2016-02-22T15:50:17.500

@ANerd-I 2 more to go 'till 16... – Conor O'Brien – 2016-04-08T05:24:54.980

@ANerd-I You're 14 total votes now. – Erik the Outgolfer – 2016-05-30T07:00:43.840

18

TeX

TeX was the first language to get its own StackExchange site.

(Note that we will show examples in plain TeX mostly; if any example is to be compiled using LaTeX, it will be clearly stated.)

10 cuff\/link

TeX works well with ligatures such as ff, fl, ffl or fi by default, i.e., it takes the correct ligature glyph from the font automatically. This is in general welcome of course, however, in some cases, it is frowned upon, such as in compound words. Compare the following two renderings of the word cufflink, the first one proper (ligature broken on the compound word boundary) and the second one improper (ligature crossing the compound word boundary). The first one is achieved by adding \/ in the code in the correct place.

enter image description here

9 \badness0

Yes, in TeX, you can define how "bad" things are :-) Well, actually, badness inserted in a paragraph of text says how bad it is if a linebreak appeared at the specific place. Some things insert their own badnesses; for instance, it is worse to hyphenate words than not to, and the non-breaking space has badness of 10000, which is, in a sense, the infinite badness in TeX's eyes. Here, we set the badness to zero. We also see that assignments in plain TeX are done by concatenating the register (\badness here) and the value; optionally we can place the equals sign in between.

Actually, the concept of penalties (badnesses) is crucial for TeX; it's a typographic system and beauty is one of the goals, and Knuth designed TeX so that only deterministic algorithms are used to break paragraphs into lines and lines into pages, to ensure at least reasonable stability.

8 \def\x{}

Simple definition. This defines a macro ("control sequence" in proper words) which does not take an argument and expands to ... well ... nothing :) (Do not be confused: "nothing" is not "relax", they substantially different.)

7 $$a+b$$ or \[a+b\]

Two snippets that somehow produce the same output, it's a displayed equation showing simple

a + b

(just centred of course). The first is the correct thing to do in plain TeX. If only people knew how wrong it is in LaTeX, where the second one should be used!

6 \relax

TeX is one of the languages that have its own "do nothing" action. However, \relax is more than just that, and this is related to the fact that it is an expansion language: All macros are expanded, and in some contexts, executed. The power of \relax is that it is executed to nothing, but it cannot be expanded, i.e., it survives any expansion unmodified. This in turn is one of the strenghts (and threats at the same time, especially for newcomers) of TeX.

5 X\bye

A minimal document that compiles producing an output; we get a page with a 10-point "X" at the top and a centred page number "1" at the bottom. ... "X," said Tom, and added, leaving: "Bye!"

4 \bye

When you say "bye" to TeX, it finishes the document; namely it closes the current paragraph if any is open, ships out the last page, and ends. Without this command, no document can be successfully produced.

3 $a$

Prints the mathematical symbol "a", that can stand for instance for a variable, function or a constant. Without the dollars, it would be the text symbol "a"; it is necessary to distinguish these two!

2 <endline><endline>

Two consecutive ends of line finish a paragraph. (One end of line behaves like a space.)

1 %

The percent sign starts a comment; the comment runs until the end of line, and eats the end of line together with leading whitespace on the next line.

yo'

Posted 2015-01-19T12:36:59.320

Reputation: 563

You have 6 more facts to add... :) – Alan Munn – 2016-06-24T23:15:41.917

17

Tcl

Unlike many other languages, Tcl has no reserved words, the control structures are just "normal" commands.

2 chars

{}

Empty string literal.

5 chars

end-1

Used as index, means the second last element.

6 chars

if 0 ?

Just a comment. Can span multiple lines.

Johannes Kuhn

Posted 2015-01-19T12:36:59.320

Reputation: 7 122

1I think you should add the {}, end-1. – jimmy23013 – 2015-01-24T09:07:42.853

17

T-SQL

Factoid: T-SQL is in fact Turing-Complete and can be proven (given enough upvotes).

bmarks

Posted 2015-01-19T12:36:59.320

Reputation: 2 114

4how many upvote do you need? XD – Kokizzu – 2015-01-23T02:49:57.357

Here is my upvote. Now prove it! Just kidding, but you still have my upvote. – Ismael Miguel – 2015-01-23T15:38:00.107

3at 8 characters I think you can actually run a command? SELECT 1 – KutuluMike – 2015-01-29T23:23:52.690

4Since the snippets don't have to be complete programs, just snippets, there are a number of things that could be done. ; is the standard terminator, although it is optional for most statements in T-SQL. -- indicates the beginning of a single line comment. SET can be used to assign values to variables and alter database and system parameters. /**/ defines a comment block. BREAK exits a loop. sp_who is a system procedure that provide information on users and processes. Please put something up for our upvotes. – MickyT – 2015-02-05T20:46:30.580

17

Vitsy

I've been wanting to put this up for ages. Here we go...

Factoid:

Vitsy is a stack-based 1D programming language with a stack composed of stacks composed of doubles. At any point, the program stack may look like this:

4 8 9      As you can see, each sub-stack may have its own unique length.
8 3 2
9 6 4      Items from the current stack will always be pulled from the top, unless 
3   3      otherwise specified by the user.
5

These would technically be doubles, but, hey, it's a representation.

Length 1 Snippet:

[

The shortest stack overflow error you'll ever see.

Basically, in Vitsy, the [ represents "start while loop". While in a while loop, the program will wrap around the line - which means it starts another while loop, which wraps around the line and starts another while...

You get it.

Length 2 Snippet:

"N

Prints the number 78 to STDOUT.

The character " captures any characters following it as a string and pushes it to the stack. Whenever Vitsy is capturing text, it wraps around the line. Therefore, N is pushed to the stack. Then, the character N prints the top item of the stack to STDOUT. ASCII Character 78 is N, therefore, 78 is printed to STDOUT.

Length 3 Snippet

Length 3... in characters.

'Nߟ

Since Vitsy reads unknown characters as NOPs and can read character values of UTF-8, the character ߟ translates to the number 2015.

Happy late welcome to 2015, everybody.

Length 4 Snippet

I\iO

Just in case you ever want to reverse an input, this will grab the input a character at a time, reversing the string in the process.

Length 5 Snippet

DmN
0

This code will always error unless the number 1 is input.

m tells the program to go to a line specified by the top item of the stack. If the number is 0, it'll duplicate the top item and go to the 0th line, the line with the m in it. This will throw the standard StackOverflowException. If it's 1, it'll go to the first line (0), push 0 to the stack, go back to where it left off (N), and push the top item of the stack to STDOUT as a number (0). If it's greater than one, or less than 0, it'll throw an ArrayOutOfBoundsException, because it doesn't know where to look for the specified line.

Length 6 Snippet

The standard quine is simply:

'rd3*Z
'      Capture all items as string until encountering another one
       of itself. If it does not find it before the end of the 
       line, it will loop around the line back to the start,
       which makes this capture all of the instructions as a string.
 r     Reverse the current stack
  d3*  Get the ASCII number of '
     Z Print everything in the stack out as a character.

I love how short this is, and it was totally unintentional. :D

Length 7 Snippet

DpD(!<N

This program will print out a single zero if the number input is not prime, and infinite 0s if it is prime. Basically, it tests if a number is prime. If it is, it skips the <, which forces a backward loop (which will always find 0 because 1, the truthy for the prime number test, is not prime.

Length 8 Snippet

R\&Yv?vN

I just realized I haven't introduced stack features. ¯\_(ツ)_/¯

Vitsy also has stack manipulators - in this example, I grab input as an integer implicitly, get a random decimal in the range [0,20) and generate that number (when looping, we use the truncated integer as the repeat count) many times. Note that this will be in the range [1, 20], as there is already a stack.

Length 9 Snippet:

00k
;use a

So, let's say that you want to use another program (called "a") in your program. So what do you do?

You import it with ;use. Then, you get the 0th index of the ;use declaration's 0th line of code (00k). Very fancy classes. This will be the basis in which I will create libraries for Vitsy. (Note that this is now ;u - the declarations were changed to only the first letter as of a later update)

Length 10 Snippet:

What's the date again?

")(etaD"nZ

Vitsy doesn't have it's own way of getting the date - but it does have JavaScript eval worked into the code. That means that I can get the date string that JavaScript returns by pushing Date() to the stack, then eval with JS (n), then outputting the entire stack (Z). Fun, huh?

Length 11 Snippet

It's getting harder to make these. D:

iG' ystiv',

Well, this code is not fun. If you have Vitsy saved as a system command (like I do), you can have problems like this. Basically, I grab the filename and push it to the stack with iG (push -1, get that index of class name), then I push 'vitsy ' behind it. Then I execute that in a shell.

forkbomb

Forkbomb = sad

Length 14 Snippet

v&v\[y1-\?v?v]

What I'm doing here is moving a prompted input number of items to a following stack. This would likely be used in a non-runnable class like so:

;
v&v\[y1-\?v?v]

And called like so:

01k
;u something.vt

Explanation:

I grab the top item of the stack (my number of items to move), make a new stack, push that number back in and repeat everything in the loop brackets that many times. y1- signifies the number of stacks currently in play minus one, so y1-\? goes to the stack previous of the one you're currently in (because I'm an idiot and never implemented going backwards - but don't worry, it'll be here soon).

Length 15 Snippet - Fibonacci!

11[XD{+DN' 'O1]

This outputs the fibonacci sequence, separated by spaces, to STDOUT infinitely.

Interestingly enough, while making this code the first time, I realized that separating by spaces (with a small delay between each output) caused parabolas to appear in the output. Go figure.

Addison Crump

Posted 2015-01-19T12:36:59.320

Reputation: 10 763

How come Date() is backwards in length 10? – GamrCorps – 2015-12-09T14:03:17.503

Vitsy is a top access only stack. When I do eval, it grabs it in reverse order of how I put it into the stack. That means that )(etaD is read as Date() by eval. @GamrCorps – Addison Crump – 2015-12-09T14:08:15.807

Ah, I see. Thanks. – GamrCorps – 2015-12-09T14:12:57.483

17

Pyke

Factoid: Pyke is a stack-based golfing language with lots of implicit inputs. It was created to be easily extendable in February 2016. It is a great language to golf in.

1 byte:

r

Try it here!

This is the shortest semi-infinite loop in Pyke (Pyke has a setting that breaks out of it early turned on by default). It is equivalent to

1: GOTO_START

r has 2 defined functions - goto_start and return. If r is visited in a function macro, it will instead return the current values on the stack.

If an error occurs whilst redoing the code again, it will go back to r and continue onwards.

2 bytes:

SB

Try it here!

The factorial function - not a builtin. Equivalent to

product(range(1, input+1))

Input is implicit in Pyke, whenever input is missing, it loads the next value off the input stack onto the program stack. At the end of the input stack there is an infinite amount of whatever the first item was. Output in Pyke is also implicit. Explicit output can also be used with the newline and p nodes for with and without a trailing newline respectively.

3 bytes:

]UP

Try it here!

This actually shows off 3 interesting features:

]   -   [input, input] - Pyke reuses the stack when already used
 U  -  2d_map(^) - Creates a 2d range, effectively an `a*b` grid
  P - pretty_print(^) - Pretty print the values keeping the same padding for every column

4 bytes

F\_+

Try it here!

This shows off Pyke's for-loops using strings. If the input to a for loop is a string and the output is a list of strings, it automatically concatinates them together. Equivalent to

rtn = []
for i in input:
    rtn.append(i+"_")
rtn = "".join(rtn)
print(rtn)

5 bytes

#.b){

Try it here!

This program outputs if the input is a Fibonacci number. It uses the up_to node to generate Fibonacci numbers up to the input and then decides if the input is in that list

      - rtn = []
      - i = 0
#  )  - while rtn[-1] <= input:
 .b   -     rtn.append(nth_fib(i))
      -     i += 1
    { - input in rtn

6 bytes

C695@]

Try it here!

Pyke has a neat function for clock related queries. The C or 'clock' takes any amount of numbers afterwards and returns a time-related thing for each of them.

  • 6 - months
  • 9 - Months of the year (1 indexed, 0 is "PADDING")
  • 5 - days

The script outputs the day of the current month as well as the name of that month.

C695   - stack = months, month_names, days
    @  - stack = month_names[months], days
     ] - stack = [month_names[months], days]

7 bytes

Finally... We got there, an absolutely minimal 'Hello World' program. Yes that is 7 bytes, in characters it is . d 0x02 0x0973 v

.dॳv

Try it here!

This uses Pyke's built in compression to stick the words 'hello' and 'world' together. . d 0x02 says that there are 2 words to be combined and the other 2 characters say which words to use.

A compressor for Pyke can be found here

8 bytes

1?tY/r"Z

Try it here!

This introduces 2 new features: Variable modification and escaping of infinite loops.

The explanation is annotated with python code to show what each character's doing

         - Y = 256
     r   - try:
         -     while True:
 ? Y     -         Y = lambda: v(Y)
  t      -             lambda x: x-1
1   /    -         stack.append(1/^)
         - except:
      "Z -     stack.append("Z")

The ? inplace variable modification node applies the first node to the contents of the second. Eventually Y will equal 0 and the 1/Y section will raise a ZeroDivisionError and will jump out of the infinite while loop.

9 bytes

S#2%!)1|e

Try it here!

Takes a list of numbers and outputs the largest even number or 0 if there are no even numbers in the list.

S         -  sorted(input)
 #   )    - filter(V, ^):
  2%!     -  not i%2
      1|  - ^ or 1
        e - if isinstance(^, int): floor_half(^)
          - else: ^[-1]

This overloads the e node which when given a list returns the last element and when given an integer, divides it by 2 and rounds down.

10 bytes

Cy1H30M"+t

Try it here!

This uses the brand new time types to add 1 hour 30 mins to the current time and drop the date part

C          -   current_time()
        +  -  ^ + V
 y1H30M"   -   time(hours=1, minutes = 30)
         t - time(^)

11 bytes

V.X".X-+||"

Try it here!

This shows off two new instructions (There are in fact only two unique ones in the program). These are the repeat V and the print_grid .X functions.

V takes an integer or iterable and repeats the code the length of that iterable or the number of times. It takes the whole stack and when it loops, the current stack is kept and fed as input. If an iterable is passed, it also pushes that iterable at the beginning.

.X is a special function in that it will probably only be used in challenges requiring a strict output format. It takes a string (with optional newlines) and pads it so it is in a grid-like format. It also optionally takes up to 8 characters to pad with:

0: upper (all characters have this as default)

1: topleft (corners if undefined have this)

2: left line

3: right line

4: lower line

5: topright corner

6: bottomright corner

7: bottomleft corner

If no characters are given, it defaults to surrounding the entire thing with spaces. The program can stop defining extra characters by ending with a ".

V           - repeat number of times:
 .X"        -  surround with spaces
    .X-+||" -  surround in a ascii box

12 bytes

Whoever said golfing languages had far to many useless builtins?

CB"Jupiter"@

Try it here!

Returns the distance Jupiter will be from Earth on the next full moon (in AU). Seriously.

C            -   current_time()
 B           -  full_moon_after(^)
  "Jupiter"@ - distance_to_earth("Jupiter", time=^)

Also works for all the planets in the solar system as well as some artificial satellites such as Voyager 2 and PIONEER 10

13 bytes

~1#_P)D3M*+mP

Try it here!

We've just gone infinite! Returns an infinite list of all the prime numbers combined with all numbers with 2 prime factors.

~1            -    An infinite list of all the natural numbers, starting from 0.
  #  )        -   filter(^ as i, V)
   _P         -    is_prime(^)
      D3      -  duplicate ^ 3 times
        M*    -   cartesian_product(^ * ^) (Return an infinite list of all numbers with 2 prime factors)
          +   -  ^ + ^^ (Return an infinite list with a semi-sorted transposition of the 2 input ones)
           mP - map(factors, ^) (Return an infinite list of the factors of the 1 and 2 factor numbers)

Infinite lists are effectively Python's generators. At the end of a Pyke program, all infinite lists on the stack are unwound as far as it will go in the time limit available (or none if done offline). Pyke has operators to filter and map nodes to infinite lists as well as combine them in various ways. Infinite lists are a relatively new feature and have been used in several short answers.

14 bytes

y0:0"wVs5
​

Try it here!

Prints out every second in a day. This could be useful for challenges where you have to filter by specific seconds.

y0:0"         - create the time "0:0" (0 hours and 0 minutes)
     w      -  86400. Takes the ordinate of `` - 32.
        V     - repeat ^ times: V
         s5   -   increment the seconds by 1
           \n -  print(^)

Both s and l change the amount of time by a predetermined amount. s increases and l decreases.

0 - years

1 - months

2 - days

3 - hours

4 - minutes

5 - seconds

6 - weeks

7 - 4 years

8 - decades

9 - 12 hours

15 bytes

.dȇጾȞĶl5

Try it here!

Again another dictionary command. It's up to you to understand what it does

Blue

Posted 2015-01-19T12:36:59.320

Reputation: 26 661

16

VB.net

(0 Code Example)

If you import the schema for a XML document, you'll get improved Intelli-sense support for the XML you are using. For example the rss schema.

Dim rss = XMLDocument.Load("path to rss")
Dim items = rss.<

At this point you'll see <channel>

Dim items = rss.<channel>.<

At this point you'll get

<title>
<link>
<description>
<language>
<pubDate>
<lastBuildDate>
<docs>
<generator>
<managingEditor>
<webMaster>
<item>

Let's continue.

Dim items = rss.<channel>.<item>
For Each item In items
  Dim title = item.<

At this point you'll get

<title>
<link>
<description>
<pubDate>
<guid>

Also it also works for xml node attributes. node.@


1 Char

! aka the Dictionary Lookup Literal can be used on dictionary retrieve the value of a key, the key used with the literal can not be a variable and thus changeable at runtime.


2 Chars (VB14 or later)

?. Null Propagation operator

Example usage.

Dim x As String
Dim c = x?.Length

is equivalent to the following code.

Dim x As String
Dim c As Nullable(of Integer)
If x Is Nothing Then
  c = New Nullable(Of Integer)()
Else
  c = New Nullable(of Integer)(x.Length)
End If

Adam Speight

Posted 2015-01-19T12:36:59.320

Reputation: 1 234

3While you don't get an upvote you must first post a single factoid about your language of choice in plain english, no code yet :-) – Will Lp – 2015-01-19T20:03:27.160

2@WillP The rules say the number of characters is upvotes plus downvotes, so (your?) downvote means he can delete the whole post and post a single character thing from the language. That said, the factoid doesn't really have to do with the language anyway, rather with the program most use to write it (Visual Studio). – IllusiveBrian – 2015-01-19T20:17:46.573

2@Namfuak It's upvotes minus downvotes in the way you'd expect. If I said otherwise somewhere then that's a typo. I downvoted this since it does not follow the "no code in the factoid" rule. But it could be fixed or Adam can delete this answer and try again. – Calvin's Hobbies – 2015-01-19T20:32:23.183

@Calvin'sHobbies Huh, now I reread it and that's pretty obviously what it says. Dunno how I misread it the first two times. – IllusiveBrian – 2015-01-19T20:37:38.317

@WillP It describing VB.net Visual Studio IDE feature, not a feature of the programming language. The "code" is showing where the feature will available. – Adam Speight – 2015-01-19T20:47:14.140

@Namfuak You have to use VB.net, to use in a programming language. – Adam Speight – 2015-01-19T20:49:05.540

@Calvin'sHobbies I could delete the "code" but without know how and where this feature is enabled, you naturally wouldn't be aware of it. – Adam Speight – 2015-01-19T20:51:18.890

My bad. I admit I just saw the code blocks and assumed it was true code. It does seem a little borderline but it's alright. I'd change my vote but it won't let me unless the answer is edited. – Calvin's Hobbies – 2015-01-19T21:02:01.337

@Calvin'sHobbies I just edited it, so you should be able to undo your vote if you want. – NinjaBearMonkey – 2015-01-19T21:13:38.963

@Calvin'sHobbies I like skirting the borderline, as it is at the fringes of the definitions. – Adam Speight – 2015-01-19T21:20:17.540

Nullable(of Integer) is equivalent to Integer?, so you should just use that instead. Then you can say c = Nothing or c = x.Length depending on the If result. And are you going to update this answer at all? If not, I could continue, since I program in VB.NET. – mbomb007 – 2016-04-20T16:08:33.947

1Where is continuation? – Qwertiy – 2016-04-21T10:34:05.467

@Qwertiy He hasn't been active since his last comment above. I could copy the data so far into a new answer and vote to delete this one? The answer barely gets started on VB.net, so I'd almost flag this as "not an answer". – mbomb007 – 2016-08-01T14:22:39.123

@mbomb007, but it alreary has 15 upvotes... – Qwertiy – 2016-08-01T14:29:34.157

@Qwertiy That's why it should be closed. Because the user obviously isn't updating it with new code. It's severely lacking in code to begin with. A new answer will get new upvotes. – mbomb007 – 2016-08-01T15:15:12.897

@mbomb007, the other way is to ask moderator to mark answer as community. Then continue it. – Qwertiy – 2016-08-01T16:33:24.273

@Qwertiy Yeah. That's probably better. – mbomb007 – 2016-08-01T16:38:17.253

16

PARI/GP

This 'language' is the combination of an interpreted language, GP, a C library called PARI, and a REPL called gp. It is a domain-specific language, specializing in algebraic number theory. You can do math very easily in GP, but some things (like string manipulation) are impractical.

Length 1: '

This command can be used to quote, but not in the usual way. 'x means "the literal polynomial x, not the value in the variable x". In postfix, it means the derivative. Tricky example: 'x' is 1 -- the derivative of the polynomial x. (But it is the 0th-degree polynomial 1, not the integer 1: 'x'==1 is true, but 'x'===1 is false since type('x') is "t_POL" not "t_INT".) ' can also be used on functions, where it means the numerical derivative: sin'(x) is the same as cos(x), up to roundoff error at least.

Length 2: <-

This command is used in set-builder notation. If you want to take a vector v and select only those values which satisfy f(x), you can run [x | x <- v, f(x)]. You can also use [g(x) | x <- v, f(x)] to apply the function g to all such terms.

Length 3: Mod

Most languages have a modulus operator, but GP also has the command Mod, which converts a number into an