Mathematica/CommonStructures

Common structures and manipulations

edit

One guiding principle in Mathematica is a unified structure behind almost all objects representable in Mathematica. For example, the expression   if entered will be represented as if it were written:

In[8]:= x^4 + 1
Out[8]= 1+x4

If the FullForm command is used on this expression however:

In[9]:= FullForm[x^4 + 1]
Out[9]= Plus[1, Power[x, 4]]

All objects in Mathematica, except atomic ones such as symbols, numbers, and strings, have the basic form head[e1, e2, ...] (which may be displayed or entered in some other fashion). For example, the head of the above expression is Plus. Lists have this structure too, where the head is List, and the elements are e1, e2, etc. The concept of head is defined for atomic objects as well (Symbol for symbols, Integer for whole numbers, etc.), but they have no extractable subparts.

This principle permits ordinary expressions unrelated to lists to be operated on with list operators:

In[10]:= Expand[(Cos[x] + 2 Log[x^11])/13][[2, 1]]
Out[10]= 2/13

The reverse can also occur -- lists can be modified to behave like ordinary expressions:

In[11]:= Map[Apply[Log, #] &, {{2, x}, {3, x}, {4, x}}]
Out[11]= {Log[x]/Log[2], Log[x]/Log[3], Log[x]/Log[4]}

where the Apply function changes the head of its second argument to that of the first, and Map behaves like the map function found in many functional languages. Note that Log[b,x] is the base b logarithm, which is converted to Log[x]/Log[b] on input.

Because of this equivalence between a regular mathematical object represented in Mathematica to that of a simple list structure, some built-in Mathematica functions permit threading, where functions map themselves over lists without much further specification. Indeed, Apply threads itself over lists when invoked as

In[12]:= Apply[Log, {{2,x}, {3,x}, {4,x}}, 1]
Out[12]= {Log[x]/Log[2], Log[x]/Log[3], Log[x]/Log[4]}

where the third argument being a 1 specifies that Apply replaces the heads of its argument only at the first level in the list, which is what we want, and is equivalent to the above example.