Math 350 - Lecture 10

Functions with multiple definitions

Function definitions revisited

Now that we know what the _ symbol means, it’s easy to see what function definitions are:

f[n_]:= 2 n + 3

f[cloud]

n_ means “an expression of any kind that we label n inside the function”. We can use the same pattern matching ideas from the last chapter to restrict how a function behaves.

Clear[f]

f[n_Integer?Positive]:= n^2 + 3

f[-2]

?f

f[3]

f[-3]

f[1.1]

Notice that f has two definitions now.

?f

We can build interesting functions with domain restrictions. Suppose we have a function that we only want to feed polynomials.

e[p__?(PolynomialQ[#, x]&)] := Expand[p, x]

Here, p__ allows multiple expressions (though not empty) and PolynomialQ checks to see that the input is a polynomial.

e[Cos[x]]

e[(x^(-1)+1)(x^2 + 3)]

How does Mathematica determine what order to apply function definitions in?

g[x_]:= x
g[x_Integer]:= x!

g[2.1]

g[cloud]

g[4]

The idea is that Mathematica tries to fit the most precise pattern matching to the most general (defaulting to the generic definition if one exists).

Clear[f]

Problem 10.2

Let’s look at the Collatz function again. The core function is f(x) = x/2 if x is even and 3x + 1 if x is odd.This time, instead of using If, we’ll use a multiple definition.

f[x_Integer?EvenQ]:=x/2
f[x_Integer]:= 3 x + 1

Notice that we don’t need to define our function for the odd numbers because any integer that isn’t even defaults to the second definition.

NestWhileList[f, 240, #>1&]

f[3]

f[5]

f[8]

Local variables and modules

Until this week, we’ve mostly been writing one line functions. More complex functions can be created with the use of Module, which also allows us to create and use local variables.

Let’s write a function that finds all of the primes less than an input n. In the following function, the variables pset and i are local and initialized in the first statement of the Module.

lPrimes[n_?Integer]:=Module[{pset={}, i=1},(* local vars *)
While[Prime[i]≤n,
pset = pset ⋃{Prime[i]};
i++];
pset]

lPrimes[20]

The idea of Module is that we can wrap complicated chunks of code into a function. Keep Module in mind!

Problem 19 - Construct an antiderivative function that can handle basic forms

Handle - Polynomials, Exponentials with positive base, x^negative

Integrate[x^2,x](* we want to reproduce this in the special cases*)

I want to integrate x^3.

PolynomialQ[x^-1,x]

int[term_, x_]:=Which[
					PolynomialQ[term,x], term x /Exponent[term x,x]
					(*MatchQ[(*a pattern that matches x^-1*)]*) 
]

int[x^-2, x]

x^2 + E^x + 7 x^7

List@@(x^2 + E^x + 7 x^7) (*this allows working term by term*)

Idea is that if we can define a single term antiderivative, we can map it onto the list of input terms.

Hint:

List@@(2^x)[[1]]