ReviseAlgo Logo

Functions

Higher-Order Functions

Functions that take or return other functions

Interview: Key functional programming concept — tested in map/filter/reduce and callback patterns

Last Updated: June 12, 2026 9 min read

Higher-order functions are functions that either take other functions as arguments, return functions, or both. This is a core concept in functional programming that enables powerful patterns like map/filter/reduce, callbacks, function composition, and the decorator pattern in Python.

Functions as Arguments

  • Callback pattern: Pass a function to be called when an event occurs or a task completes
  • Strategy pattern: Pass different functions to change algorithm behavior without modifying the function itself
  • Key functions: sorted(), min(), max() accept a key function for custom ordering
  • Apply pattern: A function that applies another function to a value — apply(func, value)

Functions as Return Values

  • Factory pattern: Return customized functions — make_adder(5) returns a function that adds 5
  • Partial application: Bind some arguments and return a function for the rest — functools.partial
  • Decorator pattern: Return a wrapper function that extends the original function's behavior

Built-in Higher-Order Functions

  • map(func, iterable): Apply function to each element — prefer list comprehensions
  • filter(func, iterable): Keep elements where func returns True — prefer filtered comprehensions
  • reduce(func, iterable): Accumulate to single value using binary function — from functools
  • sorted(iterable, key=func): Sort using a custom key function
  • any/all: Test if any/all elements satisfy a condition

Function Composition

Compose functions to build pipelines: compose(f, g)(x) = f(g(x)). This is the foundation of data processing pipelines, middleware chains, and the pipe operator concept from functional programming.

map/filter vs Comprehensions

In Python, list comprehensions are generally preferred over map/filter for readability: [x**2 for x in nums if x > 0] is clearer than list(map(lambda x: x**2, filter(lambda x: x > 0, nums))). Use map/filter when you already have a named function.

Use Cases

Data processing pipelines with map, filter, and reduce chains

Strategy pattern — swapping algorithms at runtime without changing code

Building middleware chains in web frameworks (request -> auth -> handler)

Callback-based APIs for async operations and event handling

Function composition for building complex operations from simple ones

Common Mistakes

Using map/filter with lambda when a list comprehension is more readable

Forgetting that map/filter return iterators (lazy) in Python 3 — need list() to see results

Not understanding that reduce processes left-to-right — order matters for non-commutative operations

Over-abstracting with higher-order functions when simple loops would be clearer

Confusing function composition order — compose(f, g)(x) = f(g(x)), not g(f(x))