Functional Programming
Building programs from pure functions, first-class and higher-order functions, map/filter/reduce, immutability, currying and composition.
What is it?
Functional programming (FP) builds programs by combining functions rather than by changing state step by step. Its core ideas:
- Pure functions: the output depends only on the inputs, and calling the function has no side effects (no mutation, no I/O, no global changes). Same input, same output, every time. - First-class functions: functions are values. You can store them in variables, pass them as arguments and return them. - Higher-order functions: functions that take or return other functions, like map, filter and reduce. - Immutability: instead of changing data, create new data. - Currying: turning a function of several arguments into a chain of one-argument functions: add(a, b) becomes add(a)(b). - Composition: building a new function by chaining existing ones, so the output of one becomes the input of the next.
You don't need a "functional language" to use these ideas. JavaScript, Python, Java, Rust and C# all support them, and most modern code mixes FP with other styles.
Explain like I'm 10
A pure function is a vending machine that always gives the same snack for the same button, and doesn't secretly rearrange the shop. Composition is an assembly line: each station does one job and passes the result to the next.
Examples
Pure vs impure functions (JavaScript)
// Impure: depends on and changes outside state
let total = 0;
function addToTotal(amount) {
total += amount; // side effect
return total; // result depends on history
}
// Pure: same input, same output, no side effects
function add(a, b) {
return a + b;
}
addToTotal(5); // 5
addToTotal(5); // 10 (same call, different result)
add(2, 3); // 5, alwaysmap, filter and reduce instead of a loop
from functools import reduce
orders = [
{"item": "book", "price": 12, "paid": True},
{"item": "pen", "price": 2, "paid": False},
{"item": "lamp", "price": 30, "paid": True},
]
paid = filter(lambda order: order["paid"], orders)
prices = map(lambda order: order["price"], paid)
revenue = reduce(lambda total, price: total + price, prices, 0)
print(revenue) # 42
# Idiomatic Python often uses a comprehension for the same thing:
revenue = sum(order["price"] for order in orders if order["paid"])Currying and composition (TypeScript)
const multiply = (factor: number) => (value: number) => value * factor;
const double = multiply(2); // partially applied
const addTax = multiply(1.2);
const compose =
<T>(...fns: Array<(input: T) => T>) =>
(input: T): T =>
fns.reduceRight((acc, fn) => fn(acc), input);
const doubleThenTax = compose(addTax, double); // runs right-to-left
doubleThenTax(10); // 24multiply is curried, so multiply(2) returns a reusable function. compose(f, g)(x) means f(g(x)). A pipe helper does the same left-to-right, which many people find easier to read.
How it works
Because pure functions don't depend on hidden state, a call can always be replaced by its result: referential transparency. That makes code easy to test (no setup, no mocks), safe to run in parallel, and easy to cache (memoisation).
Higher-order functions capture common loop shapes once:
map(f, xs): transform every element.filter(pred, xs): keep elements that pass a test.reduce(f, xs, init): combine elements into one value.
Real programs need side effects (reading files, writing to databases, printing). FP doesn't forbid them; it pushes them to the edges. A common design is a "functional core, imperative shell": pure functions compute decisions, and a thin outer layer performs the I/O.
Languages like Haskell enforce purity in the type system. Most mainstream languages leave it as a discipline you follow.
[orders] --filter(paid)--> [book, lamp] --map(price)--> [12, 30] --reduce(+)--> 42
compose(addTax, double)(10):
10 --double--> 20 --addTax--> 24Why does it exist?
Shared mutable state and hidden side effects make code hard to reason about, test and parallelise. FP, rooted in the lambda calculus and Lisp, offers a style where each piece can be understood on its own. The rise of multi-core CPUs, distributed data processing (MapReduce, Spark) and UI frameworks built on immutable state (React, Redux) brought these ideas into the mainstream.
When to use it
Use FP techniques for data transformations (lists of records, API responses), business rules that should be easy to test, concurrent code where shared state is risky, and callbacks or pipelines. Writing core logic as pure functions and keeping I/O at the edges is valuable in almost any codebase.
When not to use it
Don't force point-free style or deep currying where a plain loop reads better, especially in a team unfamiliar with it. Long chains of map/filter/reduce over huge arrays can create many intermediate collections; a single loop (or lazy iterators) may be faster. Some problems (simulations, games, low-level performance code) are naturally stateful and clearer with controlled mutation.
Common mistakes
Using
mapfor side effects (logging, pushing to another array) and ignoring the returned array; useforEachor a loop for side effects.Writing a
reduceso clever nobody can read it, whensum,filteror a short loop would be clearer.Thinking a function is pure while it mutates its argument (e.g.
arr.sort()inside a 'pure' helper).Forgetting the initial value in
reduce, which crashes on an empty array in both JavaScript and Python.Treating FP as all-or-nothing instead of applying pure functions where they help and keeping I/O at the edges.
Practice exercises
- Easy:
Given a list of words, use map and filter to return the uppercase versions of the words longer than 4 characters.
- Medium:
Implement your own
map,filterandreduceas plain functions (no built-ins), then implementmapandfilterusing only yourreduce. - Hard:
Write a generic
curry(fn)in JavaScript that works for any number of arguments (usingfn.length), socurry((a, b, c) => a + b + c)(1)(2)(3)andcurry(...)(1, 2)(3)both return 6.
Interview questions
What is a pure function?
A function whose result depends only on its arguments and which causes no observable side effects: no mutation of inputs or globals, no I/O. Calling it with the same arguments always returns the same result.
What is a side effect?
Any observable change a function makes beyond returning a value: modifying a variable outside its scope, mutating an argument, writing to a file, network or console, or throwing based on external state.
What does 'first-class functions' mean?
Functions are values like any other: they can be assigned to variables, passed as arguments, returned from functions and stored in data structures.
What is a higher-order function?
A function that takes one or more functions as arguments, returns a function, or both. map, filter, reduce, sorted(key=...) and decorators are examples.
What is referential transparency?
The property that an expression can be replaced by its value without changing the program's behaviour. Pure functions give you this, which enables reasoning by substitution and safe caching.
What is the difference between currying and partial application?
Currying transforms an n-argument function into n nested one-argument functions. Partial application fixes some arguments of a function and returns a function of the rest (e.g. Python's functools.partial). Curried functions make partial application easy.
What is function composition?
Combining functions so the output of one is the input of the next: compose(f, g)(x) = f(g(x)). pipe is the same idea applied left-to-right.
How do you handle side effects in a functional design?
Isolate them at the boundaries: keep business logic in pure functions and let a thin outer layer do I/O ('functional core, imperative shell'). Purely functional languages model effects explicitly in types (e.g. Haskell's IO).
Why is FP well suited to concurrency?
Pure functions over immutable data share no mutable state, so there's nothing to race on and no need for locks. Work can be split across threads or machines and results combined safely.
What does `reduce` do, and why should you pass an initial value?
It folds a collection into a single value by applying a combining function to an accumulator and each element. Without an initial value it uses the first element and throws on an empty collection, and the accumulator type may not be what you intended.