Learning path

Full curriculum

Full curriculum

Unit content

Higher-order functions and function composition

Functions can be treated as values: they can be stored, passed as arguments and returned from other functions. A function that receives or returns another function is a higher-order function.

Functions as arguments

A collection operation can receive the transformation it should apply:

map(square, values)
filter(is_positive, values)

The traversal logic is separated from the particular operation performed on each element.

Function composition

If

$$f:A\to B$$

and

$$g:B\to C,$$

then their composition is

$$g\circ f:A\to C,$$

with

$$(g\circ f)(x)=g(f(x)).$$

Composition lets small transformations form larger pipelines.

Returning functions

A function can capture configuration and return a specialized function. For example, a multiplier factory given $k$ can return the function $x\mapsto kx$.

Why composition matters

Ordinary composition works cleanly when the output of one computation has exactly the type expected by the next. Later, computations that can fail, be absent or carry some other context will break this simple pattern. map and flatMap extend the same compositional idea to those wrapped results.