Function Composition
What you'll learn: How to combine simple functions to create more complex operations by feeding one function's output into another.
The Core Idea
Function composition is the mathematical concept of chaining functions together, where the output of one function becomes the input of the next. Think of it like an assembly line: each station (function) does one specific task, and the product passes from station to station until complete.
Instead of writing one large, complicated function, you compose small, pure functions together. If you have a function f that transforms A → B and another function g that transforms B → C, composing them creates a new function that transforms A → C directly.
How It Works
In mathematical notation, composition is written as (g ∘ f)(x) = g(f(x)). You read this right-to-left: "apply f to x, then apply g to the result."
In practice, imagine you have:
- A function
doublethat multiplies a number by 2 - A function
addTenthat adds 10 to a number
Composing them (addTen ∘ double) creates a new function that doubles the input then adds 10. If you pass 5, it returns 20 (not 30).
Why Composition Matters
Function composition promotes:
- Reusability: Small functions become building blocks
- Readability: Each function has a clear, single purpose
- Testability: Test small units independently
- Reasoning: Pure functions with no side effects compose predictably
Because composition relies on pure functions and immutability (concepts you just learned), there are no hidden dependencies or state changes that break the chain.
Key Takeaway: Function composition lets you build complex transformations from simple, reusable pure functions, creating a pipeline where each function's output flows naturally into the next function's input.