Sunday, March 17, 2013

Employing "Map" to Make Mathematica More Elegant

One of Mathematica's most under-used features is its support for functional programming.  Many researchers treat Mathematica as a procedural language; that is, as though it were C or FORTRAN with interactive plotting. This certainly works but, with apologies to Dijkstra, it can lead to code that is neither simple nor clear -- in short: not what mathematicians would call "elegant".

One quick way to make your Mathematica code more elegant is to use the Map command in place of For loops when building up arrays. Map is not an outright replacement for For loops, but it can be very helpful when you are trying to transform one data set into another.

For a simple example, let's say that you need to compute the sine of a set of angles. If you were doing this in the style of a procedural programming language, your code might look like the following:
input = {0,\(\frac{\pi}{3}\),\(\frac{2\pi}{3}\),\(\pi\)};

output = Array[0,Length[input]];
For[i = 1, i \(\leq\) Length[input], i++,
   output[[i]] = Sin[input[[i]]];
];
Now, that really doesn't look so bad. It's only three lines of code.  However, it's only one idea: the transformation of a single data set. It would be more elegant if we could express this one idea in a single -- readable -- line of code. Fortunately, this is exactly the task for which Map was intended:
output = Map[Sin,input];
This statement applies the Sin command to each element of the input list and captures the results in  an output list in corresponding order. It is equivalent to the previous example in terms of behavior and speed, yet it is superior in terms of clarity because it expresses the idea more compactly.

Of course, for a single loop, the payoff in clarity will be minimal. On the other hand, if you make it a habit to express transformations in this fashion, the benefits you reap from code simplicity will grow along with your project.

No comments:

Post a Comment