Session 1 - How To: Functions and Lists

Defining Functions

The symbol := creates a delayed evaluation. When the lhs is called, it is evaluated at the time of the call

(* Define x and y as the current time - but y is evaluated delayed *)
x=Now
y:=Now
(* Print x and y *)
Print["x: ", x, " y: ",y]
(* Wait for 1 Second *)
Pause[1]
(* y is evaluated again, and has a new value *)
Print["x: ", x, " y: ",y]
Pause[1]
Print["x: ", x, " y: ",y]

Using the underscore, we can define patterns. Patterns can be used to define arguments of a function

f[x_,y_]:=x+y
f[1,3]
f[Pi,-2*Pi]

Functions may depend on undefined symbols and on variables with values. Note that the values are evaluated delayed, i.e., if a value of a variable used in a function changes, the function changes too.

Unset[a]
g[x_]:=a*x-1
g[1]
a=5;
g[1]

Lists

Lists (or Arrays) are denoted with { }. List entries are accessed with [[ ]].
Lists can contain all kinds of elements (numbers, variables, equations, functions ....)

list = {1,-1,12,4,42}
list[[3]]
(* Returns the last element in list *)
list[[-1]]
crazylist={1,Red,FindMaximumFlow,x^2≥1}
crazylist[[2]]

Lists can be nested to create multi dimensional arrays. Use the function MatrixForm (or // MatrixForm at the end a line) to create a nice,  matrix output

matrix={{1,2},{3,4}};
MatrixForm[matrix]

Mathematica contains all kinds of list- and matrix functions.

(* Dot Product *)
{{1,2},{3,4}}.{1,1}
(* Eigenvalues *)
Eigenvalues[{{1,2},{3,4}}]
(* Sum of a list/vector *)
Total[{1,2,Sqrt[42]}]

List can be created by functions, e.g., Range, ConstantArray, IdentityMatrix,...
Furthermore, arrays can be created by Table or Array

Range[10]
ConstantArray[Sqrt[42],5]
Table[i^2,{i,1,5}]
Table[(-1)^(i+j),{i,1,5},{j,1,5}]//MatrixForm
Array[Sin[#/4*Pi]&,12]

Sometimes it is useful to apply a function to all values of a list rather than applying it to the list itself.
Use Map[ ] or /@ for this purpose.

list={1,2,3,4,5,6,7};
func[x_]:=x^2+1;
func/@list
matrix={{1,2},{3,4}};
(* The last parameter specifies the level on which the function should be applied *)
Map[func,matrix,{2}]