Notebook for Class 3

September 28, 1998

Note: the following document may look like a Mathematica notebook, but it is not: it is an html document.

Procedural vs . Functional Programming

To form the sum of a list:

In[1]:=

myList = {1, 2, 3, 4, 5}

Out[1]=

{1,2,3,4,5}

Procedurally:

In[2]:=

sum = 0;
For[i = 1, i <= Length[myList], i++,
sum = sum + myList[[i]];
]
sum

Out[3]=

15

Functionally:

In[4]:=

Apply[Plus, myList]

Out[4]=

15

or, in short-hand form:

In[5]:=

Plus @@ myList

Out[5]=

15

Maps in Functional Programming

To form a list with each element the square root of myList, done in a procedural fashion, first construct an empty table to hold the answer:

In[6]:=

myNewList = Table[Null, {5}];

In[7]:=

For[i = 1, i <= Length[myList], i++,
myNewList[[i]] = Sqrt[myList[[i]]]
];
myNewList

Out[7]=

{1, Sqrt[2], Sqrt[3], 2, Sqrt[5]}

Functionally, we use the Map operator:

In[9]:=

Map[Sqrt,myList]

Out[9]=

{1, Sqrt[2], Sqrt[3], 2, Sqrt[5]}

or in short-hand form:

In[10]:=

Sqrt /@ myList

Out[10]=

{1, Sqrt[2], Sqrt[3], 2, Sqrt[5]}

Pure Functions in Functional Programming

To form the square of myList procedurally:

In[11]:=

myNewList = Table[Null, {5}]

Out[11]=

{Null,Null,Null,Null,Null}

In[12]:=

For[i = 1, i <= Length[myList], i++,
myNewList[[i]] = Power[ myList[[i]], 2]
];
myNewList

Out[13]=

{1,4,9,16,25}

Functionally, we can define a mySquare[] function:

In[14]:=

mySquare[x_] := Power[x,2]

and then:

In[15]:=

mySquare /@ myList

Out[15]=

{1,4,9,16,25}

We can avoid defining mySquare[] by using a "pure function":

In[16]:=

Map[Power[#,2]&,myList]

Out[16]=

{1,4,9,16,25}

or, perhaps more readably:

In[17]:=

Power[#,2]& /@ myList

Out[17]=

{1,4,9,16,25}

Beginning to define V[A_]

V = | det A | / (alpha1 alpha2 .... alphaN)

alphai = Sqrt[( ai1^2 + ai2^2 + ... + aiN^2 )]

Determinant[] is a built-in. We will concentrate on the denominator in a functional form.

In[18]:=

a = {{a11, a12}, {a21, a22}};

In[19]:=

MatrixForm[a]

Out[19]//MatrixForm=

a11 a12

a21 a22

In[20]:=

Plus @@ a

Out[20]=

{a11+a21,a12+a22}

This is not what we need. The two terms are the sums of the rows for a fixed columns, not the sums of the columns for fixed rows.

In[21]:=

Transpose[a]

Out[21]=

{{a11,a21},{a12,a22}}

In[22]:=

Plus @@ Transpose[a]

Out[22]=

{a11+a12,a21+a22}

In[23]:=

Plus @@ Power[#,2]& ) /@ Transpose[a]

Out[23]=

{a11^2 + a12^2, a21^2 + a22^2}

This is pretty close to a list of the alpha's.