[Question]
  [
> 
> ### Notes
> 
> 
> * This thread is open and unlocked only because [the community decided to make an exception](http://codegolf.meta.stackexchange.com/q/10656/12012). Please **do not** use this question as evidence that you can ask similar questions here. Please **do not** create additional [showcase](/questions/tagged/showcase "show questions tagged 'showcase'") questions.
> * This is no longer a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), nor are snippet lengths limited by the vote tally. If you know this thread from before, please make sure you familiarize yourself with the changes.
> 
> 
> 
This thread is dedicated to showing off interesting, useful, obscure, and/or unique features your favorite programming languages have to offer. This is neither a challenge nor a competition, but a collaboration effort to showcase as many programming languages as possible as well as possible.
### How this works
* All answers should include the name of the programming language at the top of the post, prefixed by a `#`.
* Answers may contain one (and only one) factoid, i.e., a couple of sentences without code that describe the language.
* Aside from the factoid, answers should consist of snippets of code, which can (but don't have to be) programs or functions.
* The snippets do not need to be related. In fact, snippets that are *too* related may be redundant.
* Since this is not a contest, all programming languages are welcome, whenever they were created.
* Answers that contain more than a handful of code snippets should use a [Stack Snippet](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) 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](http://codegolf.meta.stackexchange.com/q/10734/12012), 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>
```
  
[Answer]
# 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](https://codegolf.stackexchange.com/revisions/44683/24) 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](http://en.wikipedia.org/wiki/Lagrangian_mechanics) for such a system (in terms of the pendulums' angles and angular momenta). A derivation can be found [in this PDF](http://sophia.dtp.fmph.uniba.sk/~kovacik/doublePendulum.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](https://i.stack.imgur.com/61C0c.png)
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](https://i.stack.imgur.com/3WS9q.gif)
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](https://twitter.com/wolframtap/status/559290929316909056/photo/1), 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](https://i.stack.imgur.com/myQdG.png)
### 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](http://en.wikipedia.org/wiki/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](https://i.stack.imgur.com/yMhPe.gif)
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](http://en.wikipedia.org/wiki/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](http://reference.wolfram.com/language/tutorial/CellularAutomata.html). 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](https://i.stack.imgur.com/ny4Fw.gif)
### 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](https://i.stack.imgur.com/wogEW.png)
### 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](https://i.stack.imgur.com/KV8g5.png)
### 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](https://i.stack.imgur.com/D2kOl.png)
Want to detect edges? It's a single function call:
![enter image description here](https://i.stack.imgur.com/IjPwo.png)
### 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](http://en.wikipedia.org/wiki/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](https://i.stack.imgur.com/xpRH2.png)
### 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](https://i.stack.imgur.com/eF7eo.png)
### 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](https://i.stack.imgur.com/EOPuu.gif)
### Length 40 snippet
```
SortBy[PlanetData[#, "EscapeVelocity"]&]
```
`SortBy` does what you expect: it sorts a list based on values obtained by mapping a given function onto each list element. But wait, the above call doesn't contain a list at all. Since Mathematica 10, there is support for *currying* or *partial application* for some functions. This is not a language feature like in the more purist functional languages, but is just implemented manually for a whole bunch of functions where this is often useful. It means that the above snippet returns a new function, which *only* takes a list and then sorts by the given function. This can be very useful if this sorting order is something you'll use more often throughout your code.
And yes, there's another nice `*Data` function - the above will sort planet names by the planets' [escape velocities](http://en.wikipedia.org/wiki/Escape_velocity).
### 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](https://i.stack.imgur.com/RsPBo.png)
### 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](https://i.stack.imgur.com/9Bi4c.png)
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](https://i.stack.imgur.com/gdB8s.png)
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.](http://reference.wolfram.com/language/ref/CountryData.html)
![enter image description here](https://i.stack.imgur.com/y7uSQ.png)
### 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](https://i.stack.imgur.com/K3doR.png)
### 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](https://i.stack.imgur.com/T7qLM.png)
### 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](http://en.wikipedia.org/wiki/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](https://i.stack.imgur.com/WoqNQ.png)
### 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](https://i.stack.imgur.com/eqpRo.png)
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](http://en.wikipedia.org/wiki/Petersen_graph). It does produce the actual data structure that can be manipulated, but Mathematica immediately displays that graph data ... graphically:
![Mathematica graphics](https://i.stack.imgur.com/bjdhh.png)
### 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](https://i.stack.imgur.com/hncLW.png)
### 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 `lambda`s 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 `Sequence`s. 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 *d*s 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](https://i.stack.imgur.com/qGMge.png)
### 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.
[Answer]
# The Infamous [Shakespeare Programming Language](http://esolangs.org/wiki/Shakespeare)
Shakespeare Programming Language was created in 2001 by two Swedish students, Karl Hasselstr√∂m and Jon √Öslund, and it combines, as the [authors proclaim](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00030000000000000000),
> 
> 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](https://codegolf.stackexchange.com/posts/44766/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](https://shakespearelang.org/) - 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](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00070000000000000000).
Another site for running SPL code is [this one](https://apex.oracle.com/pls/apex/f?p=SPL) 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](http://shakespearelang.sourceforge.net/report/shakespeare/#SECTION00091000000000000000).
**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](https://github.com/drsam94/Spl)) 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](http://shakespearelang.sf.net/download/spl-1.2.1.tar.gz).
**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](http://flex.sourceforge.net/) and [Bison](http://www.gnu.org/software/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.
[Answer]
# [Piet](http://www.dangermouse.net/esoteric/piet.html)
**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](https://i.stack.imgur.com/eB4XY.png)
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](https://i.stack.imgur.com/lRG1h.png)
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](https://i.stack.imgur.com/rFVzV.png)
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](https://i.stack.imgur.com/m3XR2.png)
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, `push`ing 1 onto the stack twice, `add`ing the ones together, then `output`ing the result.
**5 Codels**
![5 Codels](https://i.stack.imgur.com/nYWRF.png)
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](https://i.stack.imgur.com/e8y5T.png)
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](https://i.stack.imgur.com/EnEqR.png)
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](https://i.stack.imgur.com/V9FYs.png)
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 `push`es the value 1 onto the stack, slides across the white so no command is executed, and then `pop`s 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](https://i.stack.imgur.com/yKnUm.png)
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 `push`es 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](https://i.stack.imgur.com/uGZR7.png)
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](https://i.stack.imgur.com/OjV6N.png)
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](https://i.stack.imgur.com/IiXez.png)
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](https://i.stack.imgur.com/BQKEu.png)
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](https://i.stack.imgur.com/gVE3q.png)
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 `push`es 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](https://i.stack.imgur.com/H7qdd.png)
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.
[Answer]
# [><> (Fish)](http://esolangs.org/wiki/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 `1`s 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
```
*Un*like 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 `X`s, 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](https://i.stack.imgur.com/aJS8q.gif)
**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](http://esolangs.org/wiki/Fish). 
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](https://gist.github.com/anonymous/6392418) 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](https://i.stack.imgur.com/svbW7.gif)
**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](https://i.stack.imgur.com/qvvKX.gif)
**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](https://i.stack.imgur.com/7gAn3.gif).
**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)
[Answer]
# C ‚Äì [edit](https://codegolf.stackexchange.com/posts/44698/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 `#include`d 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](http://rosettacode.org/wiki/Ackermann_function#C "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.
[Answer]
# 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](https://en.wikipedia.org/wiki/Complex_instruction_set_computing "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](https://en.wikipedia.org/wiki/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](https://i.stack.imgur.com/ym5x0.png)
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](https://i.stack.imgur.com/Ftqys.png)
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](http://www.classicdosgames.com/video/vga13.html), 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](https://i.stack.imgur.com/dNLph.gif)
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](https://en.wikipedia.org/wiki/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](https://i.stack.imgur.com/TO3fm.gif)
Pressing a non-control key will cause the program to exit. This is based off of  [Fire Coral](http://www.pouet.net/prod.php?which=64484) 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](https://en.wikipedia.org/wiki/Binary-coded_decimal) 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](https://codegolf.stackexchange.com/questions/3105/generate-a-mandelbrot-fractal), 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](https://i.stack.imgur.com/OXIgI.png)](https://i.stack.imgur.com/OXIgI.png)
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.
[Answer]
# 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 `a`s, return a list of `b`s.
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 **function**`map(^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**](https://en.wikipedia.org/wiki/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"!
[Answer]
# 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 `float`s.
## 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](https://stackoverflow.com/questions/12690128/how-to-instantiate-non-static-inner-class-within-a-static-method) [faced](https://stackoverflow.com/questions/4058974/static-method-returning-inner-class) [by](https://stackoverflow.com/questions/10672563/inner-class-and-static-method-java) [many](https://stackoverflow.com/questions/975134/why-cant-we-have-static-method-in-a-non-static-inner-class) [programmers](https://stackoverflow.com/questions/5944448/what-exactly-is-the-reason-that-we-cannot-declare-static-methods-in-public-inn?lq=1).
## 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.
[Answer]
# 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 (no longer required in C#9.0):
```
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](http://www.cs.fsu.edu/%7Emyers/c++/notes/references.html). 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.
[Answer]
# Python 2
Now starting with the newest for your convenience!
To read through length 30 starting with the earliest first, go to revision history.
If anyone has suggestions, feel free to comment.
## Length 100 üéâ
We reached 100, hurray! Because of this impressive milestone, I have updated this showcase with a new program.
```
import re
def f(i):
    w = re.sub('\s', '', i)
    s = re.subn('[\W_]', '', w)
    a = len(s[0])
    print '%d + %d = %d' % (a, s[1], a+s[1])
```
[**Try it Online!**](https://tio.run/##zY5BCsIwFET3OcUnUJLQIOpSyDm6SItEmmBA05AfKZ4@fq14BgdmBuZtJj/rdUnH1uI9L6VC8Wz2AYKM6sSAtIKhcYePixQjCg2CHNWH4Y8lKew4nKcvXzfuiN98kmj307bkElMF0c3QA4WhENCBdBrQHiYNrn@3amg45//1iQ6xIFG1Fw)
Taken from [this old answer of mine](https://codegolf.stackexchange.com/a/44532/34718), which was conveniently 100 bytes.
This program uses regular expressions on the input string to count the number of whitespace characters, then non-whitespace characters. It will then display the counts, and the sum total. This challenge had a source restriction, requiring the programs to have an equal number of whitespace and non-whitespace characters. Running this program with itself as input will print `50 + 50 = 100`.
`re.sub` is the function to replace using a regex. `re.subn` does the same thing, but also returns the number of replacements (in addition to the string after replacement). This program also uses a format string with a tuple of parameters to print in the proper format.
---
**Length 52:**
```
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](https://codegolf.stackexchange.com/a/50142/34718) challenge. `s` and `n` need to be set to a string and an integer ahead of time.
[Try It Online!](https://tio.run/##K6gsycjPM/pfbKuem1hUWJqaqm7NlWdrav0/09aAqzwjMydVoTg6UzfPKtaqoCgzr0RDXUFdK0@7WDM60ypPOzPWOlPb1tA6U0vLHIj@/wcA)
**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](https://breakingcode.wordpress.com/2010/07/23/quickpost-hiding-your-python-source-with-rot13/), 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](http://en.wikipedia.org/wiki/Complex_number). 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](http://en.wikipedia.org/wiki/Quaternion), but I digress. Read the bug/change order [here](http://bugs.python.org/issue10562) (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](https://docs.python.org/3/whatsnew/3.0.html).
**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](http://www.wefearchange.org/2010/06/import-this-and-zen-of-python.html)! 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`](https://docs.python.org/2/library/functions.html#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](https://docs.python.org/2/library/functions.html#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](https://stackoverflow.com/questions/5893163/underscore-in-python/5893946#5893946), 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](https://www.python.org/dev/peps/pep-0020/)":
* 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!
[Answer]
# JavaScript
This goes newest to oldest. Link for myself: [[edit](https://codegolf.stackexchange.com/posts/44706/edit)]  
**Length 52 snippet:**
```
console.log([...new Array(5000000)].map((a,b)=>b+1))
```
This logs an array of five million consecutive integers to the console.
**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](http://vanilla-js.com/)). 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](http://updates.html5rocks.com/2014/01/Web-apps-that-talk---Introduction-to-the-Speech-Synthesis-API). [Not yet supported by Firefox, certainly not IE](http://caniuse.com/speech-synthesis).
**Length 48 snippet:**
```
function repeat(){setTimeout(repeat,48)}repeat()
```
Simulate `setInterval` by recursively `setTimeout`ing.
**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](https://codegolf.stackexchange.com/a/21887/32376), but JS lacks `#define` and so ends up uglier. It returns, of course, [the answer to life, the universe, and everything](https://www.google.com/?q=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.](https://meta.stackexchange.com/a/19492/259693)
**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](https://en.wikipedia.org/wiki/Quine_(computing)). 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](https://codegolf.stackexchange.com/review/suggested-edits/19862))
```
+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](https://codegolf.stackexchange.com/help/badges/39/good-answer?userid=32376) 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/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](http://www.json.org/) 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"](https://stackoverflow.com/a/245068/3187556).
[Answer]
# 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](https://i.stack.imgur.com/AtXKF.png)
---
**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](https://i.stack.imgur.com/bEYHZ.png)
---
**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](http://had.co.nz). 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](https://i.stack.imgur.com/7k2DU.png)
---
**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](https://i.stack.imgur.com/bTWPM.png)
---
**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](https://i.stack.imgur.com/XZzNj.png)
---
**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](https://i.stack.imgur.com/tfg2D.png)
---
**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.
[Answer]
## [Brainfuck](http://esolangs.org/wiki/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.
[Answer]
# 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(); }`
[Answer]
# 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ÕûaÃ®tÃ¥Ã®cÕûhÃõeÕ¢Õ°sÃ∂Õò Õòa“ânÕ†ÕúÃõyÃ∏ÕÄ Õ¢cÃµÃ°haÕÅrÕòÕùaÃïÕ¢cÕÅtÕ†ÕòeÕèÕ†ÕÄrÕÄÃ∑ Õ¢Ã¥ÃïexÕùÕûÕûc“âepÕÄtÃõ ÃïfÃ¥“âoÕüÕúrÃ¥Õ¢ ÕûnÕèeÃ®Õü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
RÕûÃßeÃ°Õü“âgÕüÕ¢ÕÅeÕòÃ¢Ã¥Õ°xÕÅÃ°Õû ÃõÕÄ“â“âÃ¢c“âÃ∑Ã®aÃ∏ÕûÃõn“âÕ†Ãõ ÕÄÃ∑Ã∏pÕ†Ã¥Õ°“âÃµaÃ®ÕúÃßÕ¢rÃ∏Ã∏ÕùÃ¢Ã∑sÕ°Ã¢ÕÄeÕòÃ∑Ã∑Ã∑Õû ÕÄÃ®ÃßHÕúÃ®ÃßÕúTÃ∑ÕûMÕúÃõÃ∑LÕ¢.Ã¥Ã°ÕÅ Repeat after me. RÕ≠ÕØÃÅÕÉÃéÕÇÃàÕØÕ§ÃáÕäÕäÃ¢Ã∂ÃßÃ∂ÕüÃ∞ÃûÃ≤ÃªÃÆÃ≥Ã¶Ã•eÃÜÃΩÕÑÕ®ÃêÃΩÕ™ÕÆÃçÕÇÕêÕÆÕßÃîÃèÃìÕ£ÕÄÃ±ÃπÃ©Ã™ÕàÕàÕçÃóÕéÃùÕögÃÇÕäÕíÕ¶ÕõÕ§ÕóÕ¨ÕßÕ™ÃæÃ¢ÕòÃµÃ¢ÕüÃñÃ§ÃúÃ≠ÕîeÕ¶ÃÑÕ≠ÃëÃæ“âÃ®ÕüÕ¢Ã®ÃùÃ¨ÃπÃòÃ≠ÕîxÃæÃçÕ¶ÃëÕÑÃãÃåÃâÃéÕäÕÆÕóÃÑÃöÃöÃÜÃíÕÅÃ£ÃªÕìÃ†ÕàÕïÃ•ÃúÕöÃ±ÃùÕÖÃ´ÕöÃ≥ ÕÇÕßÕßÃÉÕêÃéÕÆÃåÕ§ÕÑÃíÃÜÕ£ÕÑÃèÃîÕäÃêÃ∏ÕÄÃ¶ÕàÃ•Ã¨Ã∫ÕácÕ®ÃÉÃøÃìÃàÕÅÃßÃ®Ã¨Ã™Ã≥Ã¶ÕéÃñÕÖÕïÃ¶ÕîaÃèÕÆÃéÕÉÃêÃ∏Õ°ÕòÕúÃïÃ≥Ã∫Ã†Ã≠nÕ≠Õ≠ÕÑÕ¶ÕÑÃΩÕóÕ•ÃëÕùÃßÃ®Õ°Ã´ÕîÕçÃ¨Ã§ÃòÕéÕöÃ£ÃüÃ¶ÕçÃú ÃçÃÑÕ≠ÕÉÕ®ÃãÕãÕÑÕóÃåÃáÕ§ÕãÕ¨ÃõÕòÃ∏ÃñÃùÃªÃªÕépÕ™ÃíÃçÕ´Õ§Õ≠ÕäÕÆÃáÃøÃÜÃöÃêÃÑÃéÕåÕèÃßÕèÕáÃºÕöÃ∞ÕìÃ≤ÕïÃ∞ÃñÃòÃüÃûÃ∫Ã≤aÃâÃäÕ£Õ≠Õ§ÃáÕ®ÕòÕ†ÃõÕÅÃ•ÕáÃ´ÃªrÕ¶ÃÇÕÑÃÜÕëÕäÕ£ÃäÕÆÃâÃöÃâÕÜÕßÃíÕõÃêÃãÕèÕ°ÕúÕûÃ¥Ã≠Ã´ÃûÃØÃòÃñÕçÃºÃñÃúÃûÃñÃ©ÕïÃπÃªÃÆÕÖÃósÕ¨ÃãÕåÃÑÕÇÕ©ÃìÃêÃîÕÉÕåÃæÃöÃÄÃàÕäÃäÕ§ÕÄÃüÕàÃ∫ÕñÃ¶ÃüÃôÃ¶ÕñÃ§eÕ´ÃêÕíÃΩÕØÕ´Õ®ÕèÃ®ÕÄÃ°ÕÅÃ¶Ã§ÃôÕçÃôÃ™ÃùÃÆÃ§ÕéÃ≠ÃñÃ™ÃªÕôÕçÕñÕâ ÃêÕóÕóÕäÃáÕ£ÕíÕóÕëÃÜÕêÃéÃêÃÄÕ¨ÕõÕÆÕùÕâÃ≠Ã´Ã∞ÕîÃùÕìÃºÃÆÕöÃªÕéÕéÕâHÕ£Õ¶ÃçÕ®ÕíÃîÃåÃ¢Ã•ÕïÃºÕìÃ´ÕôÃ∫ÃºÃÆTÕíÃëÕ≠ÃêÃëÃÉÕ≠Õ£ÕêÃéÃíÃâÕäÕúÕÄÕúÃ™Ã≤Ã¶ÃªÃ¶ÕñÃûÃ§MÕóÕßÃåÕØÕãÕÇÃâÃçÕ≠ÃìÃáÃêÃåÕúÕ†ÃûÃ™ÕáÕïÃ©ÕâLÃÅÕõÕåÕ≠ÃâÃçÃ®Ã∑Ã≥ÃòÃØÕöÕì.ÕØÕÜÃäÃåÕØÃáÃìÃèÕêÕ™ÃãÕÑÕëÃï“âÃ∑ÕÄÕÅÃ†Ã∞ÃºÃ§Ã≤
[Answer]
## J
PS: Snippets now linked to [tryJ.tk](http://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](http://www.jsoftware.com/jwiki/FrontPage) is a descendant of APL (see [here](http://keiapl.org/rhui/remember.htm#sec1) for the family history) minus the funny character set.
### [Length 1 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=_)
```
_
```
J uses `_` both as [infinity and as negative indicator](http://www.jsoftware.com/help/dictionary/d030.htm), when attached to number literals (opposed to the verb `-`).
### [Length 2 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=a.)
```
a.
```
`a.` is called [Alphabet](http://www.jsoftware.com/jwiki/Vocabulary/adot), 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=i.9)
```
i.9
```
[`i.`](http://www.jsoftware.com/help/dictionary/didot.htm) 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=!!6x)
```
!!6x
```
J supports [arbitrary precision integer and rational numbers](http://www.jsoftware.com/help/dictionary/dcons.htm). This calculates the factorial of the factorial of 6 (a 1747 digit number).
### [Length 5 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%5E.%5E%3A_%20%5D3)
```
^.^:_ 
```
A dense one... First, verbs (as J calls functions) are organized by theme. All ^ verbs are tied to exponentiation. `^` for [exponentiation](http://www.jsoftware.com/help/dictionary/d200.htm) (and `exp` when used monadically, `^.` for [logarithms](http://www.jsoftware.com/help/dictionary/d201.htm). `^:` is a special one, the [Power](http://www.jsoftware.com/help/dictionary/d202n.htm) 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%5E0j1p1)
```
^0j1p1
```
or equivalently
```
^o.0j1
```
[Euler's Identity](http://www.jsoftware.com/jwiki/Essays/Euler%27s%20Identity) 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%2B%2F%26.%3A*%3A%203%204%205%206)
```
+/&.:*:
```
A verb taking the 2-norm of any vector. This demonstrates 2 things:
* the [Insert](http://www.jsoftware.com/help/dictionary/d420.htm) 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](http://www.jsoftware.com/help/dictionary/d631.htm) when used as `v &.: u y` is equivalent to `vi u v y`, where `vi` is the [obverse](http://www.jsoftware.com/help/dictionary/dbdotu.htm) (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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%24%23%3AI.%40%3A%2C)%205%20%3D%20i.%205%205)
```
$#:I.@:,
```
A [fork](http://www.jsoftware.com/help/dictionary/dictf.htm) 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"](http://www.jsoftware.com/help/dictionary/dicapdot.htm) returns the indices of ones in a vector, but does not extend to higher dimensions as such.
This example uses [Shape](http://www.jsoftware.com/help/dictionary/d210.htm), [Antibase](http://www.jsoftware.com/help/dictionary/d402.htm) 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%3C%221%20i.4%206)
```
<"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](http://www.jsoftware.com/help/dictionary/d010.htm) 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](http://www.jsoftware.com/help/dictionary/dbdotu.htm) 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](http://www.jsoftware.com/help/dictionary/d600n.htm), 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](http://www.jsoftware.com/jwiki/Essays/Rank).
### [Length 10 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%5D%3B%20%3C.%2F%20.%2B%7E%5E%3A_%20)%20wtm%3D%3A%20_6%5D%5C0%202%205%20_%20_%20_%20_%200%204%201%203%20_%20_%20_%200%20_%20_2%20_%20_%20_%204%200%20_%205%20_%20_%20_%20_1%200%206%20_%20_%20_%20_%20_%200)
```
<./ .+~^:_
```
This snippet is a verb calculating the [shortest path](http://www.jsoftware.com/jwiki/Essays/Floyd) over weighted digraph.
It introduces minimum (`<./`) and the [Dot conjunction](http://www.jsoftware.com/help/dictionary/d300.htm).
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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%3C.%40o.10x%5E99)
```
<[[email protected]](/cdn-cgi/l/email-protection)^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](http://www.jsoftware.com/jwiki/Vocabulary/SpecialCombinations))
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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%24%20%28%28%24-.1%3A%29%28%24%2C%29%5D%29%20i.%202%201%203%201%201%205)
```
($-.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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(_2%20%2B%20*%3A)%20(1%20%3A%27-u%25u%20d.%201%27)%5E%3A_%20%5D%201)
```
1 :'-u%u d.1'
```
[Newton's Method](http://www.jsoftware.com/jwiki/Essays/Newton%27s%20Method) finds an approximation of a root of a differentiable function.
This [explicit adverb](http://www.jsoftware.com/jwiki/Vocabulary/Modifiers) 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](http://www.jsoftware.com/jwiki/Vocabulary/hook) subtracting the [fork](http://www.jsoftware.com/jwiki/Vocabulary/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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%25-.-*%3A)t.i.10)
```
(%-.-*:)t.i.10
```
First 10 numbers of the [Fibonacci series](http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sequence) by Taylor expansion of
`x / (1 - x - x^2)`. Analyzing the hook `%-.-*:` gives  `(y % (-.-*:) y) = (y % ( (1 - y) - *: y)`.
### [Length 15 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%23%7B.%2B%2F%2F.)!%2F%7Ei.9)
```
(#{.+//.)!/~i.9
```
Another take on Fibonacci series. This time from another angle; starting from Pascale's triangle '!/~i.9' .
`/` when used dyadically means [Table](http://www.jsoftware.com/help/dictionary/d420.htm), 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)](http://www.jsoftware.com/help/dictionary/d410.htm). `~` makes the verb [Reflexive](http://www.jsoftware.com/help/dictionary/d220v.htm), 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%3C%2F.%20!%2F%7E%20i.5) )
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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%3B%2F%40%7E.%2C.%3C%220%40%23%2F.%7E)%201%202%203%202%203%202%203%202%203%201%203)
```
;/@~.,. <"0@#/.~:
```
Ok, I added a space just to get to 16 :). This snippet demonstrates a fork using [Key](http://www.jsoftware.com/help/dictionary/d421.htm):
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](http://www.jsoftware.com/help/dictionary/d000.htm),
which generates a boolean array containing 1's in positions where they appear in the `nub` [~.](http://www.jsoftware.com/help/dictionary/d221.htm)
Here it's applied reflexively, hence executing [Tally](http://www.jsoftware.com/help/dictionary/d400.htm)
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](http://www.jsoftware.com/help/dictionary/d321.htm) 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](http://www.jsoftware.com/papers/rank.htm), this code works [for any dimensionality](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=(%3B%2F%40%7E.%2C.%3C%220%40%23%2F.%7E)%20%3F%20100%202%202%242).
### [Length 17 snippet](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%5Dn%3D%3A%20(p%3D%3A%3F!9)%20*.%2F%20%40%3A(%23%26%3E)%40C.%40A.%20i.9)
```
*./ @:(#&>)@C.@A.
```
J supports a few primitives specifically about permutations:
* [Anagram A.](http://www.jsoftware.com/help/dictionary/dacapdot.htm) 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.](http://www.jsoftware.com/help/dictionary/dccapdot.htm)
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](http://www.jsoftware.com/help/dictionary/d111.htm) `*./` 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28bins%3D%3A%28%25%7E%3E%3A%40i.%2910%29%20%28%20%5B%20%28graph%3D%3A%28%2C%26%22%3A%220%201%20%27%23%27%23%220%201%7E%5D%29%29%20%28hist%3D%3A%3C%3A%40%28%23%2F.%7E%29%40%28i.%40%23%40%5B%20%2C%20I.%29%29%20%29%20%28%2B%2F%25%23%29%20%3F5%20200%20%24%200)
```
<:@(#/.~)@(i.@#@[,I.)
```
This little verb comes from the "stats/base" add-on, and is called [*histogram*](http://www.jsoftware.com/jwiki/Essays/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.`](http://www.jsoftware.com/help/dictionary/dicapdot.htm) 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](http://www.jsoftware.com/help/dictionary/d421.htm) 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](https://a296a8f7c5110b2ece73921ddc2abbaaa3c90d10.googledrive.com/host/0B3cbLoy-_9Dbb0NaSk9MRGE5UEU/index.html#code=%28%27abcd%27%3B1%202%203%204%29%20%28%3D%2C%26%28%2B%2F%29%28%7E%3A%23%5B%29e.%26%7E.%7E%3A%23%5D%29each%20%28%27bacd%27%3B4%201%202%203%29)
```
=,&(+/)(~:#[)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.
[Answer]
## [RPL (Redstone Programming Language)](http://tossha.com/rpl/) [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](http://meta.codegolf.stackexchange.com/a/7397/36670) (in Minecraft).
### Factoid:
RPL is a programming language by [Tossha the Inventor](https://www.youtube.com/channel/UCvH7xdcFYPpCYXHBX2TzUmA) 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](https://i.stack.imgur.com/IXcAh.png)](https://i.stack.imgur.com/IXcAh.png)
## 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](https://i.stack.imgur.com/wPo9u.png)](https://i.stack.imgur.com/wPo9u.png)
## 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](https://i.stack.imgur.com/GYVrr.png)](https://i.stack.imgur.com/GYVrr.png)
## 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](https://i.stack.imgur.com/SJSdH.png)](https://i.stack.imgur.com/SJSdH.png)
[Answer]
# 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.](http://web.archive.org/web/20150217125442/http://robertkotcher.com/sed.html)
### 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 `q`uits 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 coreutils tools.
### Length 3 Snippet
```
iHi
```
`i`nserts "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 `d`eleted 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 `b`ranches (jumps) to it. Ad infinitum.
### Length 6 Snippet
```
N;/a/d
```
The `N` command is very useful when you want information on lines `N`ext to what you're looking for; it appends an extra line to the pattern space. This will remove any pair of lines (starting from the first line) that match a regex `a`
### 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 `0`s with `1`s and vice versa.
### Length 9 Snippet
```
1!G;$p;h
```
This snippet is 8 bytes, but requires the -n parameter for sed to suppress default output. As per standard code-golf rules, I'm counting this as 9. This uses something called the 'hold space', which is essentailly a place to store something you want later. `1!` means 'on every line but the first', `G` appends the hold space to the pattern space, `$p` means `p`rint when on the last line, and `h` replaces the hold space with the current pattern space for us to `G`rab on the next cycle. So:
```
sed -n '1!G;$p;h'
```
is exactly equivalent to:
```
tac
```
### Length 10 Snippet
```
s/[ <TAB>]+$//
```
This is a revisit of the (old) length 6 snippet. This strips trailing whitespace (spaces and TABs) from lines.
### Length 11 Snippet
```
sed -n '/a/{N;N;p}'
```
The `{` command does exactly what you think it does: it groups a bunch of commands together until there's a `}`. As with most commands, you can restrict it to a range or a regex; so this program will `p`rint lines containing regex `a` along with the two `N`ext lines following them.
### Length 12 Snippet
```
'1,4d;9,/^$/d'
```
Speaking of restricting to ranges or regex, you can even do both at the same time. The first command `d`eletes lines 1-4 (counting the 1st line as line 1) and the second `d`eletes line 9, and then continues deleting until (and including) it hits an empty line.
### Length 13 Snippet
```
'/i/,/a/s/a/A/'
```
(Read '/i/,/a/' as a range and then 's/a/A/' as the commnad) If you start a range with a regex, sed will start a new range each time you hit that regex. This capitilizes the first `a` after each line with an i. (it also capitalizes the first a on the same line as an `i`, if there is one; the second address is not checked until the range starts)
### Length 14 Snippet
```
:l;N;$!bl;p;p;
```
The fisrt bit loads the entire input into the pattern space: define label `l`, add a line to pattern space, `b`ranch to `l` if we're not(`!`) the last line(`$`). In total, this program `p`rints the entire input three times: once for each `p`, and then again at the end with the default output.
### Length 15 Snippet
```
'/a/,+9d;/i/,~5d'
```
GNU Sed adds some interesting ranging options in addition to the earlier ones. `,+#` will match `#` lines following the first address and `,~#` will continue to match until the line number is divisible by `#`.
### Length 16 Snippet
```
'5,10w output.txt'
```
and
```
'r insertfile.txt'
```
Sed has a way to act directly on files with a command option (`-i` for edit-`i`n-place, with an optional backup file using `-i.bak` or whatever other suffix you want to add) but you can technically read and write to files inside your script. However, be careful when using them; `r`, for example, will output the entire file at the end of each cycle rather than appending it to the input as you may expect it to. To do this, just give each file name as another command line option like:
### Length 17 Snippet
```
sed -s '1F' in.txt file.txt
```
The `-s` command lets you treat each added file as an entirely new group of lines, starting the line count over and reseting your ranges. This script, for example, will print the current `F`ilename whenever it hits the first line of a file, allowing you to see where one file ends and the next begins.
### Length 18 Snippet
```
'N;N;P;D;P#comments'
```
Sed is pretty small in terms of built in commands, so we've almost covered everything. Several commands have a uppercase version which does things one line at a time for when you decide to load more lines into the pattern space with `N`: `P`rint up to first newline, `D`elete up to the first newline, etc. This is also a good a time as any to mention `#` makes the rest of the line into a comment, and will not be executed.
### Length 18 Snippet
```
sed ':l;N;$!bl;e' srpt.sh
```
Coming full circle to rendering other commands in sed, this is roughly the same as `sh srpt.sh`. The first bit we talked about earlier, loading the full input into the pattern space; and the `e`xecute command runs the pattern space as a bash script and replaces the pattern space with the resulting output. In this example that means it just prints with the standard end-of-cycle output. You can disable `e`, as well as `r` and `w`, with the `--sandbox` command line option.
### Length 19 Snippet
```
sed '/\\\//,//s///g' --debug
```
The `--debug` option is a great help whenever sed does something completely unexpected, as it shows each step sed takes in each cycle. It tells you, for each cycle: where the input is coming from, the new pattern space, the hold space if there is any, each command that is run with the results of that command, and the end of cycle output. It also renders your sed program in a more readable multiline form at the very start.
In this case, what happens is that an empty regex `//` is replaced with the most recently used regex when an empty regex wouldn't make sense. Since ranges are active whenever they are open, this is the same as just doing `'s/\\\///'`; ie it `s`waps each `\/` with an empty string.a
### Length 20 Snippet
```
sed -nE 's/(a|b{2})/\u\1/gp'
```
The last thing I want to mention is the `-E` extended regex option, and a few fancy things on the `s`wap command. `-E` allows you to use characters for their regex meaning rather than their literal meaning. There are also many 'backslash escapes' you can incorperate into your replace string; used here are `\u` for 'next letter uppercase' and `\1` for 'first capture group'. Finally, many standalone commands have a 'flag version' that work at the end of a `s`wap statement, like the `p` which prints if there was a successful swap.
[Answer]
# 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 *ax*2 + *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](https://i.stack.imgur.com/a00ek.png)](https://i.stack.imgur.com/a00ek.png)
### 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](https://en.wikipedia.org/wiki/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](https://en.wikipedia.org/wiki/E_(mathematical_constant)), which displays as `2.718281828`.
### Factoid
Variables can only store certain datatypes. For example, `A` ‚Äì `Z` (and `θ`) store numerical values, `str0` ‚Äì `str9` store strings, and `[A]` ‚Äì `[J]` store matrices (2-dimensional arrays).
[Answer]
# Python
*([mbomb007](https://codegolf.stackexchange.com/a/44749/21487)'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](http://www.numpy.org/) 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 *im*mutable. 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](https://www.python.org/dev/peps/pep-3132/) (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](https://docs.python.org/2/library/functions.html#round), `round` tiebreaks by rounding away from 0.
* In [Python 3](https://docs.python.org/3.5/library/functions.html#round), `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](https://en.wikipedia.org/wiki/Rounding#Round_half_to_even), 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](https://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes). 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 *im*mutable ‚Äì 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](http://emptysqua.re/blog/python-increment-is-weird-part-ii/).
### Length 16 snippet
```
@lru_cache(None)
```
Just add cache! This is a simple example of a [decorator](http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/) 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
[Answer]
# APL
## Factoid
APL (**A** **P**rogramming **L**anguage) started out as an interpreter for a formula notation devised by [Ken Iverson](https://de.wikipedia.org/wiki/Kenneth_E._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 **i**ota **o**rigin.
## 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
0 1 2
0 1 2
```
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](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#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](https://codegolf.stackexchange.com/a/44684/26997) 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‚çµ}`.
[Answer]
# [Jot](https://web.archive.org/web/20131101213211/http://semarch.linguistics.fas.nyu.edu/barker/Iota/)
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](http://en.wikipedia.org/wiki/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](http://en.wikipedia.org/wiki/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](http://en.wikipedia.org/wiki/Combinatory_logic) to Jot. This Jot program is the [K combinator](http://en.wikipedia.org/wiki/Combinatory_logic#Examples_of_combinators).
## 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](http://en.wikipedia.org/wiki/Halting_problem).
[Answer]
# 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.
[Answer]
# 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](https://i.stack.imgur.com/aj3x1.png)](https://i.stack.imgur.com/aj3x1.png)
### 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](https://i.stack.imgur.com/IkVJ9.png)
### Snippet 22 - music
```
load handel;sound(y,Fs)
```
It will sound about like [this (youtube link)](https://www.youtube.com/v/wIIH5Bva738&start=9&end=19&autoplay=1)
### 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](https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method) 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](https://i.stack.imgur.com/avwYe.png) ![with unwrap](https://i.stack.imgur.com/qgqwJ.png)
```
[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](https://i.stack.imgur.com/fa8sV.png)
### 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](https://i.stack.imgur.com/WE7ae.png) (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](https://i.stack.imgur.com/WQDAC.png)
### 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](https://i.stack.imgur.com/v4JtZ.png)
### 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](https://i.stack.imgur.com/1uLLs.png) ![spy easteregg](https://i.stack.imgur.com/yF1Wh.png)
### Snippet 9
```
kron(a,b)
```
The `kron` function evaluates the [Kronecker product](https://en.wikipedia.org/wiki/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](//stackoverflow.com/q/18553210))
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.
[Answer]
# 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#)`.
[Answer]
# 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.](http://okmij.org/ftp/Computation/Computation.html#Makefile-functional)
### 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](https://www.gnu.org/software/make/manual/make.html#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.
[Answer]
# CJam
[Try the below snippets here](http://cjam.aditsu.net/)
**Length 20 snippet:**
```
q~{]__~z\z<=\~*0>*}*
```
[A min-mod calculator](https://codegolf.stackexchange.com/a/42081/31414). 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](http://sourceforge.net/p/cjam/wiki/Variables/). 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)
[Answer]
# 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 `Future`s 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`.
## 17
### Snippet
```
({type I[T]=T})#I
```
### Explanation
This is a type lambda (in this case acting like an identity function for types). It's a combination of a type member (mentioned above) (`type I[T]` declares a type constructor `I` taking a type parameter `T` ), a structural type (everything between the braces denotes a type), and a type projection (`#I` accesses the member `I` of the structural type in braces).
In Scala 3, this can be expressed much more nicely as `[T] =>> T`.
## 18
### Snippet
```
list.reduce(_ ^ _)
```
### Explanation
Underscores have [various uses](https://stackoverflow.com/q/8000903) in Scala. Here, we can use them to define a trivial function more concisely. The `_ ^ _` is really shorthand for `(a, b) => a ^ b`.
The snippet reduces a list of what may be integers by XOR-ing them. `reduce` is just one of the many useful methods in the standard library. There are many others, such as `map`, `heads`, `distinct`, `groupBy`.
[Answer]
# 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](https://codegolf.stackexchange.com/questions/40073/making-future-posts-runnable-online-with-stack-snippets/40808#40808), for the python interpreter, you have to explicitely include each file. The inplementation of these boards can be found [on github](https://github.com/marbelous-lang). 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 `00`value 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*.
[Answer]
# 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 [`.\"`](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Displaying-characters-and-strings.html#index-g_t_002e_005c_0022-_0040var_007b-compilation-_0027ccc_0022_0027-_002d_002d-_003b-run_002dtime-_002d_002d---_007d--gforth-2013) 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](https://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Number-Conversion.html).
## 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](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/Notation.html#index-types-of-stack-items-171) that is even followed by [the standard](https://www.taygeta.com/forth/dpans.html).
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.
]