Functions

\(Needs["Graphics`Master`"]; 
Needs["Calculus`Master`"]; \)

Anonymous Functions

Function[s, s^2]

Function[s, s^2][5]

Function[s, s^2][y]

Alternatively one can use the "(#)&" construction: "#" denotes the placeholder, "(..)&" delimits the anonymous function.

(#^2)&

(#^2)&[5]

(#^2)&[y]

"Set" Functions

f[x_] = x^2

f[5]

f[y]

Don't forget the "_" to denote a variable:

g[x] = x^2

g[5]

g[y]

A "set" function evaluates all parameters when it is set first!

Clear[f, g, x, y]

a = 3f[x_] = a x^2f[y]

a = 4f[y]

"Set Delayed" Functions

A "set delayed" function evaluates all parameters every time it is executed!

Clear[f, a]

a = 3f[x_] := a x^2

f[y]

a = 4f[y]

f[x^2 + 5]

More Complicated Functions

Clear[f, a]

Functions of several variables:

f[x_, y_] = x^2 + 2  y^2

f[3, 1]

f[x^2, y^3]

Functions of lists:

norm[x_] := Sqrt[Inner[Times, x, x, Plus]]

norm[{1, 2}]

norm[{5, 1, -3}]

norm[{-3}]

norm[3]

g[x_] = 2^x

g[{1, 2, 3}]

g[3]

g[x_] := Select[x, PrimeQ]

g[{1, 2, 3, 4, 7, 9, 23}]

Step Functions:

f[x_] := 0 /; (x <= 0)\(	f[x_] := 1 /; \((x > 0)\)\)

Plot[f[x], {x, -3, 3}, 
      PlotStyle -> {AbsoluteThickness[2], Blue}];

g[x_] := x/2 /; EvenQ[x]\(	g[x_] := 3  x + 1 /; OddQ[x]\)

g[2]

g[17]

ListPlot[Table[g[x], {x, 1, 50}], PlotJoined -> True, 
      PlotStyle -> Blue];

A better solution for "normal functions" is the command "UnitStep":

Plot[UnitStep[x], {x, -3, 3}, 
      PlotStyle -> {AbsoluteThickness[2], Blue}];

h[x_] := 
      -Sin[x] + (x - (-Sin[x])) UnitStep[x] + 
        ((2 - x^2) - x) UnitStep[x - 1]

Plot[h[x], {x, -3, 3}, 
      PlotStyle -> {AbsoluteThickness[2], Blue}];

Integrate[h[x], {x, -3, 3}]

h2[x_] := -Sin[x] /; (x <= 0)\(	h2[x_] := x /; \((x > 0\  && \ x <= 1)\)\)\(	h2[x_] := 2 - x^2 /; \((x > 1)\)\)

Plot[h2[x], {x, -3, 3}, 
      PlotStyle -> {AbsoluteThickness[2], Blue}];

Integrate[h2[x], {x, -3, 3}]

Clear[g, a]

g[a_] := 
      Plot[Sin[a π x], {x, -1, 1}, 
        PlotStyle -> {AbsoluteThickness[2], Blue}]

g[1];

Table[g[i], {i, 1, 5}];

An Example Using Recursion: The Factorial Function

5!

\(fact1[1] = 1; 
fact1[n_] := n\ fact1[n - 1]\)

Table[fact1[k], {k, 1, 10}]

Trace[fact1[5]]

\(fact2[1] = 1; 
fact2[n_] := \(fact2[n] = n\ fact2[n - 1]\)\)

Table[fact2[k], {k, 1, 10}]

Trace[fact2[11]]

fact3[n_] := Product[k, {k, 1, n}]

fact3[10]

fact4[n_] := Apply[Times, Table[i, {i, 1, n}]]

fact4[10]

Another Example Using Recursion: Pascal's Triangle

\(\(pascal[0] = {1}; 

    pascal[n_Integer] := 
      \(pascal[n] = 
	
        Append[MapThread[
            Plus, {pascal[n - 1], 
              Prepend[Rest[RotateRight[pascal[n - 1]]], 0]}], 1]\)
	\)\)

TableForm[Table[pascal[i], {i, 0, 10}]]

Etc

Helmut Knaust, email: helmut@math.utep.edu. Created 3-22-1999.