Skip to main content
24 of 38
added 1698 characters in body
Martin Ender
  • 196.9k
  • 66
  • 445
  • 971


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. For some real gems, check out snippets 23, 19, 12 and 8.

Length 41 snippet


I almost forgot about Thread! Say you have two lists of things and you want to apply some operation to each pair of values at corresponding indices. Of course, you could iterate of the length of both lists, or you could join them, transpose the array, apply the operation to each element. But Thread makes this so much easier. This basically pushes down the top-level Head (type/function) down one level. So the above evaluates to:


And <> is string concatenation, so it gives


Thread can be really convenient, e.g. if you want want to piece together systems of equations from separate left-hand sides and right-hand sides.

Length 40 snippet

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

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

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

Length 39 snippet


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

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

Length 38 snippet


Another plot. This is a 2D plot which colours all space for which the given conditional expression is true. This can be very useful for plotting regions for which you only have an implicit form. The above produces:

enter image description here

If you want to look at a more elaborate use, I've used this in the past for some code golf challenges.

Length 37 snippet


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

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

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

Length 36 snippet

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

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

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

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

Length 35 snippet


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

enter image description here

Length 34 snippet

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

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

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

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

Length 33 snippet


A very nice feature David Carraher recently brought up in another of Calvin's Hobbies' challenges. Mathematica, comes with a whole bunch of example data, including test images, textures, audio snippets and 3D models (like the Utah teapot). Lena has a pretty short name and is fairly well-known, so I picked her:

enter image description here

Length 32 snippet


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

enter image description here

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

Length 31 snippet


Some more combinatorics. The above gives you all 3-element permutations taken from the given list. No permutation will appear twice, even if list contains duplicates:

{{1, 1, 1}, {1, 1, 3}, {1, 1, 4}, {1, 3, 1}, {1, 3, 3}, {1, 3, 4}, {1, 4, 1}, {1, 4, 3}, {3, 1, 1}, {3, 1, 3}, {3, 1, 4}, {3, 3, 1}, {3, 3, 4}, {3, 4, 1}, {3, 4, 3}, {4, 1, 1}, {4, 1, 3}, {4, 3, 1}, {4, 3, 3}}

Length 30 snippet


Like almost everything, Fourier transforms are computed exactly, if possible:


Length 29 snippet


Piecewise lets you define functions with different definitions for different parts of their domain. They render like you would write them in standard mathematical notation:

enter image description here

Just to showcase, how it works, if you plotted this from -5 to 5, you'd get

enter image description here

Length 28 snippet


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

enter image description here

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

Length 27 snippet

CountryData["ITA", "Shape"]

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

enter image description here

Length 26 snippet


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

enter image description here

Length 25 snippet


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

{53, 43, 92}

Length 24 snippet


Another nice feature, Mathematica can give you the Taylor expansion of any function about any point. The above gives you all terms up to order 9 of an arcsin:

SeriesData[x, 0, {1, 0, 
 Rational[1, 6], 0, 
 Rational[3, 40], 0, 
 Rational[5, 112], 0, 
 Rational[35, 1152]}, 1, 10, 1]

displayed as

enter image description here

Length 23 snippet

Rotate[Rectangle, Pi/2]

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

enter image description here

Length 22 snippet


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


Length 21 snippet


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

1/2 Sqrt[π] Erf[x]

Length 20 snippet


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

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

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

which is displayed as

enter image description here

Length 19 snippet


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

Mathematica graphics

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

Length 18 snippet


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

Mathematica graphics

Length 17 snippet


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

Mathematica graphics

Length 16 snippet


Partition is a very convenient list manipulation function, and it comes with a ton of overloads. The above is the one I'm using most often. It will give you all sublists of l of length 2 (the 1 is there to make the lists overlap). So if l was {1,2,3} you'd get

{{1, 2}, {2, 3}, {3, 4}}

Length 15 snippet


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

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


We would get


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

Length 14 snippet


This is a way to construct a list. Array invokes its first argument (a function itself) for every integer value from 1 to the second argument. So the above gives a list of the first 9 primes:

{2, 3, 5, 7, 11, 13, 17, 19, 23}

Length 13 snippet

l~Riffle~" "

First, this shows another way to call functions with two arguments. x~f~y is infix notation for f[x,y] which often saves a byte when golfing. Second, Riffle is a pretty convenient function, which takes a list and some value and ... well ... riffles the list with that value. E.g., the above example puts a space after every element of l (except the last).

Length 12 snippet


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

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

Length 11 snippet


Some combinatorics. This gives all n-tuples that can be formed with the elements of a list l. So e.g. if l was {1,2,3} and n was 2, you'd get

{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}

Length 10 snippet


With Mathematica 10, we have @* as a new operator for an old function: Composition. The above defines f to be a function that first applies Cos and then Exp to its argument. Sso f[Pi] would give you 1/E. There is also /* which is RightComposition and would apply the left-hand argument first.

Length 9 snippet


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

Length 8 snippet


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

enter image description here

Length 7 snippet


This snippet shows off a few cool things.

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


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

Length 6 snippet


Back to maths! Number literals in Mathematica can be entered in any base up to 36, using lower- or upper-case letters (or mixing them). This even works for floating point numbers, but I don't have enough characters right now to add in a decimal point to show this.

Anyway, the above is H5 (digits 17, 5) in base 23, which evaluates to 396.

Length 5 snippet


Mathematica has a built-in "type" for colours, and with that comes a whole bunch of predefined colours. The nice thing is that it actually displays as that colour in Mathematica:

enter image description here

Taking this even further, you could now copy that little coloured square and use it anywhere in your code, just like any other value or variable.

Length 4 snippet


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

Length 3 snippet


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

Length 2 snippet


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

Length 1 snippet


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


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

Martin Ender
  • 196.9k
  • 66
  • 445
  • 971