Higher-Order Function

Context: FIT1008_MOC · relies on functions being first-class · pairs with Generator Expression and List Comprehension · the f in a Tree Traversal

Quick Revision

  • 🎯 Objective: a function that takes and/or returns a function ➔ makes behaviour a parameter.
  • 📦 Core Components: closures, currying/partial, map/filter/reduce, decorators.
  • ⚡ Key Constraint: an ordinary -overhead call; total cost = number of applications (e.g. over a collection).

📝 Core

1. The HOF (First-Class Functions)

  • Definition ➔ takes a function as argument and/or returns a function.
  • Enabled by ➔ functions being first-class objects (assignable, storable, passable, returnable).
  • Payoff ➔ behaviour becomes a parameter ➔ foundation of map/filter/reduce and the callback f in a Tree Traversal.

2. The HOF Toolkit

  • Closure ➔ inner function capturing enclosing-scope variables (outlives the outer call).
  • Currying/partial ➔ f(a,b)→f(a)(b) (functools.partial).
  • map/filter/reduce ➔ transform / select / aggregate ➔ compose into pipelines.
  • Decorator ➔ a HOF wrapping a function (@dec is f = dec(f)) ➔ memoisation rescues naive Fibonacci.

⚙️ Core Implementation

🔹 Taking, returning, and the three list HOFs

⚖️ Core Decision Matrix

ToolFormReplaces / adds
mapmap(f, xs)a transform loop
filterfilter(p, xs)a select loop
reduce/foldreduce(g, xs, init)an accumulate loop
closureinner fn capturing scopeconfigured functions
partial/currypartial(f, a)specialise a general fn
decorator@dec = f = dec(f)wrap (logging, memoise, timing)

When It Flips: abstraction/reuse (one traverse(tree, f) covers infinitely many behaviours) + composability ( pipelines); the trade-off is that nested closures / point-free style can obscure control flow.

📊 Exam Execution Trace

Manual Execution Trace

A lazy select→transform→aggregate pipeline:

Step / StateStageCallStreams
0 (Init)———
1filterfilter(p, xs)keep odds
2mapmap(f, ...)square each
3reducereduce(add, ...)sum

With generators the whole pipeline is memory (no intermediate lists).

Applied Exercise

Problem: Show a decorator is a HOF. Derivation Proof / Hand-Calculation Walkthrough:

Final Extracted Output: @lru_cache memoisation turns naive Fibonacci from to — a HOF wrapper.

🧠 Active Recall