Loading...
Functions can be values as well as named routines. Read their input and result types to distinguish applying a function from merely referring to it.
What you'll be able to do
A function type A→B says allowed inputs come from domain A and results belong to co-domain B. The actual range may use only part of B. A function taking a pair of integers can be modelled as integer×integer→integer, where the Cartesian product supplies the pair.
Function application supplies actual input to obtain a result. Referring to a function without applying it can instead produce the function value. In Python, square names the function while square(3) calls it; confusing these leads to wrong higher-order arguments or premature evaluation.
A first-class function can appear in expressions, be assigned to a name, be passed as an argument and be returned as a result. Other common values, such as integers, are first class too; the term describes permitted uses rather than computational speed.
Returning a function lets a program produce specialised behaviour. A closure can retain access to values from its defining environment. These capabilities can support functional styles in multi-paradigm languages, without claiming that every function written in Python is pure or free of side effects.
A curried type integer→integer→integer is read as integer→(integer→integer). Supplying the first integer returns a function waiting for the second. Partial application fixes some arguments of a multi-argument function, creating a new function that needs the remaining ones.
Argument order matters. Fixing the first argument of subtract(a,b)=a-b to 10 gives a function producing 10-b, not b-10. Python functools.partial can demonstrate partial application even though an ordinary two-argument Python function is not automatically a curried function.
from functools import partial
def subtract(a, b):
return a - b
from_ten = partial(subtract, 10)
print(from_ten(3))
def add(a):
return lambda b: a + b
print(add(4)(6))Scroll horizontally to see the full code or table.from functools import partial
def volume(length, width, height):
return length * width * height
fixed_base = partial(volume, 2, 3)
print(fixed_base(4))Scroll horizontally to see the full code or table.Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.