Higher-Order Functions
Passing Behavior Through Functions
A higher-order function accepts a function as an argument, returns a function, or does both. You use higher-order functions when the same procedure should work with different rules: adjusting measurements, selecting records, or calculating charges. The central skill is recognizing when a program handles a function value and when it actually calls that function. The examples here use Python 3 and named functions.
Recognize the function boundary
Writing advance refers to a function. Writing advance(3) calls that function and produces its result. Passing the first expression lets another function decide when to perform the operation; passing the second supplies an already computed value.
Example: You want to apply the same adjustment twice. Define the adjustment separately from the procedure that repeats it:
def advance(x):
return x + 2
def apply_twice(fn, x):
return fn(fn(x))
result = apply_twice(advance, 3)For this particular higher-order operation, the governing relationship is:
The inner call changes 3 to 5. The outer call changes 5 to 7, so result is 7. The parameter fn receives the function itself, while x receives a number.
Classification depends on the arguments and results crossing a function's boundary, rather than the calculation inside its body.
Function behavior | Higher-order? | Reason |
|---|---|---|
Accepts a number and returns its square | No | Neither input nor output is a function |
Accepts a function and applies it twice | Yes | An argument is a function |
Accepts a number and returns a configured function | Yes | The result is a function |
Use callbacks to vary behavior
A callback is a function supplied to another function for that receiving function to call. In the example, advance serves as the callback. Replacing it changes the adjustment while leaving the repetition procedure unchanged. Pass the function itself when the receiving operation needs to call it later.
Two common Python operations illustrate different uses of callbacks. map(fn, items) applies fn to each item. filter(test, items) retains each original item for which test returns a true value; it does not replace the item with that truth value.
Both operations return iterators in Python 3. Using list(...) consumes their results and collects them into a list. For a finite input list, list(map(fn, items)) calls fn once per item, while list(filter(test, items)) tests every item, including those it discards.
Return a function for later use
A function can also produce behavior as its result. Here, make_adder acts as a function factory:
def make_adder(offset):
def add(x):
return x + offset
return add
shift = make_adder(5)
result = shift(10)Calling make_adder(5) creates and returns add. It does not yet perform an addition. The returned function can use the offset from that factory call, so the later call shift(10) returns 15.
The outer function is higher-order because it returns a function. The inner add accepts a number and returns a number. Creating a function and calling the created function are separate events.
What to remember
- A higher-order function accepts a function, returns a function, or does both.
- Parentheses with arguments call a function; its name can refer to the function value.
- A callback supplies behavior that the receiving function can apply.
- Returning a function makes that behavior available for a later call.
Example: Configuring and Applying Delivery Fees
Example: A courier charges a fixed 4 dollars per parcel plus a selected rate per kilogram. Its Python program uses a function factory, a function that creates and returns another function, to configure the rate. All parcel masses below are in kilograms, and all charges are in dollars.
def make_fee(rate):
def fee(mass):
return 4 + rate * mass
return fee
def total_after(transform, values):
total = 0
for value in values:
total = total + transform(value)
return total
parcel_fee = make_fee(3)
masses = [2, 5, 6]Assume no taxes, discounts, or additional charges.
a) Identify the two higher-order functions. Explain what parcel_fee refers to after its assignment.
The function make_fee accepts a numeric rate and returns the inner function fee, so it is higher-order because its output is a function.
The function total_after accepts the function argument transform, so it is higher-order even though its output is a number.
The assignment calls make_fee(3) and stores the returned function in parcel_fee. That function uses a rate of 3 dollars per kilogram. Returning the function does not calculate a parcel charge. A mass must be supplied in a later call.
Therefore, the two higher-order functions are make_fee and total_after, and parcel_fee refers to the returned fee function. The inner fee itself takes a number and returns a number.
b) Calculate parcel_fee(5).
First identify the values used by the returned function. The selected rate is ________, and the supplied parcel mass is ________.
Multiply the rate by the mass to find the variable charge. This gives ________, since the kilogram units cancel:
Then add the fixed charge:
The call parcel_fee(5) returns 19 dollars.
c) Calculate total_after(parcel_fee, masses) and state how many times the returned fee function is called.
The parameter transform receives the function value parcel_fee. The loop calls it once for each of the three masses; it does not call the factory again.
Calculate the charge for each parcel:
The running total after the first two parcels is ________. Adding the final parcel gives:
Thus, the returned total is 51 dollars, and the fee function is called three times. As a check, the parcels have a combined mass of 13 kg: three fixed charges plus the mass-based charge give 3(4)+3(13)=51 dollars.
A game simulation updates a player's score using the Python code below. What score does the final call return? Answer in points, to the nearest whole point.
def reward(score):
return 2 * score + 1
def apply_n(fn, value, n):
for _ in range(n):
value = fn(value)
return value
final_score = apply_n(reward, 4, 3)A game applies a bonus only to qualifying scores using this Python 3 program. Determine how many times qualifies is called and the sum of the values in adjusted. Give an exact whole-number count of calls and the total in points, to the nearest whole point.
def qualifies(score):
return score >= 9
def bonus(score):
return score + 4
scores = [6, 9, 14, 3]
kept = list(filter(qualifies, scores))
adjusted = list(map(bonus, kept))