Functions
A function is a relation between and where for each there is a exactly one such that . In other words:
We write
Domain & Range
For a function , is the domain of and is the co-domain.
The set is the range of .
- is the possible inputs of
- is the return type of
- range is the all possible outputs from
Domain Problem
Consider the function , is not defined for , but we still call it a function with domain
Function Examples
Non-Math Function Examples
- - input a student number, output the last name of the QUT student
- - input a bit string , output the MD5 hash of the bit string.
Non-Function Examples
-
- let , then could be 2 or -2.
Composing Functions
Suppose we have , . Then we can define:
This is called of of .
Inverse Function
Some functions have a partner, called its inverse. Give , the inverse is a function such that:
- The range of must match the domain of
- The domain of must match the range of
Not all functions have inverses. For example, has no inverse.
Functions in Python
Python has its own notion of what a function is, and it isn't the same!
However, Functions in Python that are side-effect free and deterministic are also functions in the mathematical sense.
What is side-effect?
- modify the state of the program (including I/O).
What is a deterministic function?
- Deterministic means that there is no randomness.
Function Examples in Python
# function in the mathematical sense
def f(x):
return x + 1
x = 10
# modifies state, not a function in mathematical sense
def changeX():
global x
x += 1
# not deterministic, not a function in mathematical sense
import random
def rand():
return random.randint(1,6)
Partial Functions
A partial function from a set to a set is a function from a subset of to .
In terms of relation, partial function contains at most one pair (a,b) for every . This is different from a function which requires exactly one pair.
Dictionaries as Partial Functions