Mathematica/Paradigms

Multiple programming paradigms
Mathematica permits multiple approaches to programming. Consider this example: we want a table of values of gcd(x, y) for 1 &le; x &le; 5, 1 &le; y &le; 5.

The most concise approach is to use one of the many specialized functions:

In[3]:= Array[GCD, {5, 5}] Out[3]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}}

There are at least three other approaches to this: In[4]:= Table[GCD[x, y], {x, 1, 5}, {y, 1, 5}] Out[4]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}}

An APL-style approach: In[5]:= Outer[GCD, Range[5], Range[5]] Out[5]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}} Outer corresponds to the generalized outer product operator, Range corresponds to the iota operator. Outer admits general functions, whether they be named, or anonymous. Anonymous functions are specified by using #n to as the function argument and appending an &. The above function could be equivalently specified as Outer[GCD[#1, #2] &, Range[5], Range[5]].

An approach using loops: In[6]:= l1 = {}; (* initialize as empty list, since we want a list in the end *) Do[l2 = {}; Do[l2 = Append[l2, GCD[i, j]], {j, 1, 5}]; l1 = Append[l1, l2], (* append the sublist, that is, the row *) {i, 1, 5}]

In[7]:= l1 Out[7]= {{1, 1, 1, 1, 1}, {1, 2, 1, 2, 1}, {1, 1, 3, 1, 1}, {1, 2, 1, 4, 1}, {1, 1, 1, 1, 5}} Observe that this solution is considerably larger than the previous ones.