Showcase of Languages Notes

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

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



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

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

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

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

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

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

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

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


Answers that predate these guidelines should be edited. Please help updating them as needed.
Current answers, sorted alphabetically by language name


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


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

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

Length 143 and 144 snippets

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

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

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

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


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



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

Graphics@{Line@{{0,0},p=θ~(h={Sin@#@#2,-Cos@#@#2}&amp;)~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:



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 -&gt; 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 -&gt; GeoStyling["ReliefMap"]]


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



Length 81 snippet

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


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

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



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

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


Length 69 snippet

DSolve[r^2*R''[r]+2r*R'[r]-R[r]==0&amp;&amp;(R[r]==1&amp;&amp;R'[r]==2/.r-&gt;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] -&gt; 1/2 r^(-(1/2) - Sqrt[5]/2) (1 - Sqrt[5] + r^Sqrt[5] + Sqrt[5] r^Sqrt[5])}}


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

Length 64 snippet

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


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

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

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



Length 59 snippet

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


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



Length 52 snippet

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


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



Length 48 snippet

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


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

Length 45 snippet

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


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



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



Length 44 snippet

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


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

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



Length 43 snippet

HighlightGraph[graph,FindVertexCover@graph]


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



Length 42 snippet

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


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



Length 40 snippet

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


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

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

Length 39 snippet

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


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

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

Length 37 snippet

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

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

Length 36 snippet

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


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

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

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

Length 35 snippet

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


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



Length 34 snippet

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


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

{
  {x -&gt; 0}, 
  {x -&gt; -(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 -&gt; -(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 -&gt; -(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&lt;2^x,{x,-2,5}]


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



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

Length 28 snippet

Graphics3D@{Sphere[],Cone[]}


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



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

Length 27 snippet

CountryData["ITA", "Shape"]


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



Length 26 snippet

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


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



Length 25 snippet

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


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

{53, 43, 92}


Length 23 snippet

Rotate[Rectangle, Pi/2]


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



Length 22 snippet

30~ElementData~"Color"


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

SlateGray


Length 21 snippet

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


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

1/2 Sqrt[π] Erf[x]


Length 20 snippet

"Sun"~StarData~"Age"


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

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

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


which is displayed as



Length 19 snippet

MandelbrotSetPlot[]


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



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

Length 18 snippet

PetersenGraph[7,2]


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



Length 17 snippet

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


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



Length 15 snippet

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


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

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

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


We would get

{4,5,1,2,3}


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

Length 12 snippet

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


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

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


Length 9 snippet

Exp[I*Pi]


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

Length 8 snippet

Sunset[]


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



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.