Programming Search⌘K

Conceptcore

Functional programming

Also called FP, functional style, pure functions, purity, referential transparency, map filter reduce, function composition, functional core imperative shell.

Functional programming builds a program from pure functions and values that do not change, and joins small functions into larger ones with higher-order functions and composition.

Applies to
core-languages

Idea

Functional programming builds a program from functions that compute a result from their arguments and do nothing else. A function of this kind does not change a variable, a data structure or the outside world, so a call with the same arguments always gives the same result. Data does not change after it is made. To get a changed value, a program builds a new one. Functions are values too, so they can be passed to other functions, returned from them and joined into new functions:

from functools import reduce

orders = (("pen", 3, 2), ("book", 1, 12), ("ink", 2, 5))


def line_total(order):
    _, qty, price = order
    return qty * price


def bulk(order):
    return order[1] > 1


bulk_totals = map(line_total, filter(bulk, orders))
print(reduce(lambda acc, x: acc + x, bulk_totals, 0))
print(tuple(o[0] for o in orders if not bulk(o)))
print(orders[0])
Output
16
('book',)
('pen', 3, 2)

The program states what it computes: the totals of the bulk orders, added up. It does not keep a running total in a variable or change the orders. Each function can be tested alone, because its result depends only on its argument.

How it works

Pure functions. A function is pure when its result depends only on its arguments and the call has no other effect. The Python HOWTO states the ideal: "functions only take inputs and produce outputs, and don't have any internal state that affects the output produced for a given input."1 John Hughes put the same point as "A function call can have no effect other than to compute its result."2 Because a pure call can be replaced by its value, a reader can reason about the code as about algebra. This property is called referential transparency. Hughes noted that in such programs "one can freely replace variables by their values and vice versa".2

Immutable data. If values never change, two parts of a program can share a value with no risk, and an old version of a structure stays valid after a new version is made. Functional languages use persistent data structures, such as linked lists and balanced trees, in which a new version shares most of its parts with the old one. A change then costs a small number of new nodes and not a full copy. See immutability.

Functions as values. A function can take functions as arguments and return functions. These are higher-order functions. The common ones are map, which applies a function to each element, filter, which keeps the elements that pass a test, and fold or reduce, which combines the elements into one value. MDN describes reduce as a method that "executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element."3 A function that is returned from another function keeps the variables of its scope, so it is a closure.

Recursion instead of loops. A loop needs a variable that changes on each pass. A pure program expresses repetition with recursion or with a higher-order function that hides the loop. Functional languages eliminate tail calls, so a recursive call in the last position runs in constant stack space.

Expressions instead of statements. In a functional language, almost everything is an expression with a value: a conditional, a block, a match. John McCarthy's paper on LISP introduced the conditional expression for this purpose, and he wrote that its use "permits functions to be defined recursively in a new and convenient way."4

Effects at the edges. A program must read input and write output at some point. Pure languages such as Haskell, which its report calls "a general purpose, purely functional programming language",5 describe effects as values of a type such as IO and let the run-time system perform them. Most other languages allow effects anywhere, and the functional style keeps them in a thin outer layer. The Python HOWTO notes that programs in this style "provide a functional-appearing interface but will use non-functional features internally."1

Why it helps. Hughes argued that the main gain is modularity, not the absence of assignment. A problem can only be divided into parts as far as the language can join the parts again, and "functional languages provide two new, very important kinds of glue".2 The two kinds of glue are higher-order functions and lazy evaluation.2 Pure code is also easier to test, because a test needs only arguments and an expected result, and easier to run in parallel, because pure calls do not share mutable state.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript, with readonly arrays and properties, function types and discriminated unions checked at compile time.
GoIdiom
RustNative
KotlinNativeLambdas, higher-order functions on collections, read-only collection interfaces, data classes with copy, and sealed classes with when; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applySQL is declarative, and a query describes a result without side effects, but SQL has no functions as values.
BashIdiom
PowerShellIdiomScript blocks are values, and the pipeline with ForEach-Object and Where-Object maps and filters objects; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no functions.
CSSDoes not applyCSS has no user-defined functions as values.
Regular expressionsDoes not applyA regular expression describes text and has no functions.
Language Verdict Mechanism
Python native lambda, comprehensions, map, filter, functools, itertools, tuples; no tail call elimination
JavaScript native arrow functions, closures, map, filter, reduce, spread copies, toSorted
TypeScript native as JavaScript, with readonly types and discriminated unions
Java native lambdas, java.util.function, streams, records, List.of
Kotlin native lambdas, collection functions, read-only collections, data classes with copy
C# native lambdas, Func, LINQ, records with with, pattern matching
Go idiom functions as values and closures; loops are the usual style
Rust native closures, iterators, immutable by default, enums with match
C idiom function pointers; no closures
C++ native lambdas, std::function, algorithms, range views
Bash idiom pipelines compose programs; no functions as values
PowerShell idiom script blocks and the pipeline
SQL n/a declarative queries; no functions as values
Regex, HTML, CSS n/a no functions

Python, JavaScript and C# are multi-paradigm languages that took the tools of functional programming without the rules. They have functions as values, closures and the standard higher-order functions, but their containers are mutable, and nothing checks that a function is pure. The functional style in these languages is a discipline of the programmer. C# added LINQ and later records, and Microsoft's guide says that constructs "such as lambda expressions and type inference make functional programming much easier".6

Java added lambdas and streams. The java.util.stream package gives "functional-style operations on streams of elements, such as map-reduce transformations on collections".7 The documentation warns that the results of a pipeline "may be nondeterministic or incorrect if the behavioral parameters to the stream operations are stateful".7 This is the rule of purity, stated as a requirement for correct parallel streams.

Rust takes the most from functional languages among the systems languages. Its book says that "one significant influence is functional programming".8 Variables are immutable unless marked mut, enums and match come from ML, and iterator chains compile to loops with no extra cost.

C and Go support the style only in part. C has function pointers but no closures, and Go has closures and generics but leaves map and filter out of its standard library, so the usual Go code is a loop. Bash composes whole programs with pipes, which is the same idea at the level of processes.

PythonGitHub
from functools import reduce
from itertools import accumulate


def compose(*fs):
    return reduce(lambda f, g: lambda x: g(f(x)), fs, lambda x: x)


words = ("map", "filter", "reduce", "fold", "zip")
shout = compose(str.upper, lambda s: s + "!")
print([shout(w) for w in words if len(w) > 3])
print(reduce(lambda acc, w: acc + len(w), words, 0))
print(list(accumulate([3, 1, 4, 1, 5])))
print(sorted(words, key=len))
print(words)
Output
['FILTER!', 'REDUCE!', 'FOLD!']
22
[3, 4, 8, 9, 14]
['map', 'zip', 'fold', 'filter', 'reduce']
('map', 'filter', 'reduce', 'fold', 'zip')

This code runs but gives a wrong answer on purpose.

def top_two(scores):
    scores.sort(reverse=True)
    return scores[:2]


scores = [70, 95, 80]
print(top_two(scores))
print(scores)
Output
[95, 80]
[95, 80, 70]
  • Verdict: native. Functions are values, and lambda, comprehensions, generators, map, filter, functools.reduce and itertools support the style. Tuples and frozenset are immutable.
  • Python is not built for pure code. It has no tail call elimination, so deep recursion fails, and most built-in containers are mutable. The functional HOWTO says that Python programs in this style usually give "a functional-appearing interface" and use assignment inside.
  • In the wrong block, list.sort changes the list of the caller. Use sorted(scores, reverse=True), which returns a new list.
#include <algorithm>
#include <iostream>
#include <numeric>
#include <ranges>
#include <string>
#include <vector>

int main() {
    const std::vector<std::string> words{"map", "filter", "reduce", "fold", "zip"};

    auto lengths = words | std::views::filter([](const auto& w) { return w.size() > 3; })
                         | std::views::transform([](const auto& w) { return w.size(); });
    for (auto n : lengths) std::cout << n << " ";
    std::cout << "\n";

    auto total = std::accumulate(words.begin(), words.end(), std::size_t{0},
                                 [](std::size_t acc, const std::string& w) { return acc + w.size(); });
    std::cout << total << "\n";

    auto compose = [](auto f, auto g) { return [=](auto x) { return g(f(x)); }; };
    auto inc_then_double = compose([](int x) { return x + 1; }, [](int x) { return x * 2; });
    std::cout << inc_then_double(5) << "\n";
}
Output
6 6 4 
22
12
  • Verdict: native. C++ has lambdas, std::function, the algorithms of <algorithm> and <numeric>, and lazy range views. const and constexpr mark values that do not change.
  • A lambda that captures by reference can outlive the variables it refers to. Capture by value when the lambda escapes.
JavaGitHub
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {
    record Order(String item, int qty, int price) {}

    public static void main(String[] args) {
        List<Order> orders = List.of(new Order("pen", 3, 2), new Order("book", 1, 12), new Order("ink", 2, 5));

        int total = orders.stream()
                .filter(o -> o.qty() > 1)
                .mapToInt(o -> o.qty() * o.price())
                .sum();
        System.out.println(total);

        Function<String, String> trim = String::strip;
        Function<String, String> slug = trim.andThen(String::toLowerCase).andThen(s -> s.replace(' ', '-'));
        System.out.println(slug.apply("  Pure Functions  "));

        System.out.println(orders.stream()
                .collect(Collectors.groupingBy(o -> o.qty() > 1, Collectors.counting())));
    }
}
Output
16
pure-functions
{false=1, true=2}
  • Verdict: native. Java has lambdas, method references, the interfaces of java.util.function and streams. The java.util.stream package describes itself as "Classes to support functional-style operations on streams of elements".
  • List.of and records give immutable values. The stream documentation warns that results "may be nondeterministic or incorrect" when a lambda in a pipeline is stateful.
#include <stdio.h>
#include <stdlib.h>

typedef int (*binop)(int, int);

static int add(int a, int b) { return a + b; }
static int max(int a, int b) { return a > b ? a : b; }

static int fold(const int *xs, size_t n, int acc, binop f)
{
    for (size_t i = 0; i < n; i++)
        acc = f(acc, xs[i]);
    return acc;
}

static int by_value(const void *a, const void *b)
{
    int x = *(const int *)a, y = *(const int *)b;
    return (x > y) - (x < y);
}

int main(void)
{
    int xs[] = { 3, 1, 4, 1, 5 };
    size_t n = sizeof xs / sizeof xs[0];
    printf("%d %d\n", fold(xs, n, 0, add), fold(xs, n, xs[0], max));
    qsort(xs, n, sizeof xs[0], by_value);
    for (size_t i = 0; i < n; i++)
        printf("%d ", xs[i]);
    printf("\n");
    return 0;
}
Output
14 5
1 1 3 4 5 
  • Verdict: idiom. C has function pointers, so a function can take another function, as qsort does. C has no closures: state for the callback must be passed by hand, often as a void * argument. const marks data that a function promises not to change.
var orders = new[] { new Order("pen", 3, 2), new Order("book", 1, 12), new Order("ink", 2, 5) };

var total = orders.Where(o => o.Qty > 1).Select(o => o.Qty * o.Price).Sum();
Console.WriteLine(total);

Func<string, string> trim = s => s.Trim();
Func<string, string> lower = s => s.ToLowerInvariant();
Func<string, string> slug = s => lower(trim(s)).Replace(' ', '-');
Console.WriteLine(slug("  Pure Functions  "));

var cheaper = orders[1] with { Price = 10 };
Console.WriteLine($"{cheaper} {orders[1]}");
Console.WriteLine(orders.Aggregate(0, (acc, o) => acc + o.Qty));

record Order(string Item, int Qty, int Price);
Output
16
pure-functions
Order { Item = book, Qty = 1, Price = 10 } Order { Item = book, Qty = 1, Price = 12 }
6
  • Verdict: native. C# has lambdas, the delegate types Func and Action, LINQ, records with with expressions, and pattern matching. Microsoft's guide says that new constructs "such as lambda expressions and type inference make functional programming much easier".
  • Aggregate is the name of fold in LINQ.
JavaScriptGitHub
const orders = Object.freeze([
  { item: "pen", qty: 3, price: 2 },
  { item: "book", qty: 1, price: 12 },
  { item: "ink", qty: 2, price: 5 },
]);

const total = orders
  .filter((o) => o.qty > 1)
  .map((o) => o.qty * o.price)
  .reduce((sum, x) => sum + x, 0);
console.log(total);

const pipe = (...fs) => (x) => fs.reduce((acc, f) => f(acc), x);
const slug = pipe((s) => s.trim(), (s) => s.toLowerCase(), (s) => s.replaceAll(" ", "-"));
console.log(slug("  Pure Functions  "));

const repriced = orders.map((o) => ({ ...o, price: o.price * 2 }));
console.log(repriced[0].price, orders[0].price);
console.log(orders.toSorted((a, b) => a.price - b.price).map((o) => o.item));
Output
16
pure-functions
4 2
[ 'pen', 'ink', 'book' ]
  • Verdict: native. Functions are values, arrow functions capture their scope, and arrays have map, filter and reduce. The spread syntax builds a changed copy of an object.
  • Object.freeze is shallow, and array methods such as sort and reverse change the array in place. The methods toSorted, toReversed and with return new arrays.
package main

import (
	"fmt"
	"strings"
)

func Map[T, U any](xs []T, f func(T) U) []U {
	out := make([]U, 0, len(xs))
	for _, x := range xs {
		out = append(out, f(x))
	}
	return out
}

func Filter[T any](xs []T, keep func(T) bool) []T {
	var out []T
	for _, x := range xs {
		if keep(x) {
			out = append(out, x)
		}
	}
	return out
}

func Reduce[T, A any](xs []T, acc A, f func(A, T) A) A {
	for _, x := range xs {
		acc = f(acc, x)
	}
	return acc
}

func main() {
	words := []string{"map", "filter", "reduce", "fold", "zip"}
	long := Filter(words, func(w string) bool { return len(w) > 3 })
	fmt.Println(Map(long, strings.ToUpper))
	fmt.Println(Reduce(words, 0, func(n int, w string) int { return n + len(w) }))
}
Output
[FILTER REDUCE FOLD]
22
  • Verdict: idiom. Go has functions as values, closures and generics, but the standard library has no Map, Filter or Reduce for slices, and the usual style is a loop. Slices and maps are mutable, and there is no way to mark a value as immutable.
RustGitHub
#[derive(Debug, Clone)]
struct Order {
    item: &'static str,
    qty: u32,
    price: u32,
}

fn main() {
    let orders = vec![
        Order { item: "pen", qty: 3, price: 2 },
        Order { item: "book", qty: 1, price: 12 },
        Order { item: "ink", qty: 2, price: 5 },
    ];

    let total: u32 = orders.iter().filter(|o| o.qty > 1).map(|o| o.qty * o.price).sum();
    println!("{total}");

    let compose = |f: fn(u32) -> u32, g: fn(u32) -> u32| move |x| g(f(x));
    let inc_then_double = compose(|x| x + 1, |x| x * 2);
    println!("{}", inc_then_double(5));

    let items = orders.iter().fold(String::new(), |acc, o| if acc.is_empty() { o.item.to_string() } else { acc + "," + o.item });
    println!("{items}");

    let cheaper = Order { price: 10, ..orders[1].clone() };
    println!("{} {}", cheaper.price, orders[1].price);
}
Output
16
12
pen,book,ink
10 12
  • Verdict: native. Rust has closures, iterators with map, filter and fold, enums with match, and variables that are immutable unless marked mut. The Rust book names functional programming as "one significant influence" on the design.
  • Rust allows mutation, but the borrow rules stop a value from being changed while other code reads it.
BashGitHub
printf '%s\n' map filter reduce fold zip |
    awk 'length($0) > 3' |
    tr 'a-z' 'A-Z' |
    sort
Output
FILTER
FOLD
REDUCE
  • Verdict: idiom. A pipeline composes programs that read input and write output, much as function composition joins functions. Each stage is a filter or a map over lines. The shell has no functions as values and no closures.
  • Pure and impure languages. Haskell keeps effects in types and has no mutable variables in ordinary code. The ML family, Scheme, Clojure, F#, Elixir and Scala are functional but allow effects anywhere.
  • Strict and lazy evaluation. Most functional languages evaluate arguments before a call. Haskell evaluates an expression only when its value is needed. See laziness.
  • Typed and untyped. The ML family and Haskell infer types with Hindley-Milner and use sum types and pattern matching. The Lisp family is dynamically typed.
  • Point-free style. Functions are defined by composition alone, with no named arguments, for example count = length . filter even.
  • Function-level programming. John Backus proposed a style in which programs are built only from functional forms that combine other functions, with no variables at all.9
  • Functional core, imperative shell. A common design in mainstream languages: the logic is pure, and a thin outer layer does the input, output and state.
  • Dataflow and reactive programming. A program is a graph of pure transformations over streams of values.

Pitfalls

  • Hidden mutation. Many library functions change their argument in place, such as list.sort in Python or Array.prototype.sort in JavaScript. A function that calls them on its argument is not pure, and the caller sees the change.
  • Shallow immutability. Object.freeze in JavaScript, final in Java and readonly in TypeScript protect only the top level. The objects inside can still change.
  • Deep recursion. Python, Java, JavaScript engines and Go do not eliminate tail calls, so a recursive loop over a long list can overflow the stack. Use a loop or a higher-order function in these languages.
  • Copies in a loop. Building a new array or string on each step of a loop, for example with spread inside reduce, costs quadratic time. Use a persistent structure, a builder, or a local mutable value that does not escape.
  • Effects inside a pipeline. A map callback that logs, counts or writes a file makes the result depend on the order and the number of calls. Lazy pipelines and parallel streams can run the callback fewer times, more times or in another order.
  • Unreadable chains. A long chain of anonymous functions can be harder to read than a loop. Name the steps.

Cost

Pure code allocates more. Each change makes a new value, and a persistent tree update makes O(log n) new nodes where an in-place update writes one word. The garbage collector must then reclaim the old versions. Closures cost an allocation when they capture variables and a call through a pointer that the compiler may not inline. Good compilers remove much of this. Rust, C++ and the JIT compilers of Java and C# inline iterator chains into plain loops. GHC fuses list pipelines so that no intermediate list is built. In return, pure code needs no locks to share data between threads, and a value can be cached or computed again freely, because a call always gives the same result.

History

The theory came first. Alonzo Church defined the lambda calculus in the 1930s as a system in which everything is a function. In 1960, John McCarthy described LISP, a language for symbolic computation built on recursive functions, conditional expressions and lists.4 Peter Landin showed in the 1960s how to describe ALGOL with lambda expressions and designed ISWIM. In his 1977 Turing Award lecture, published in 1978, John Backus said that conventional languages had a "primitive word-at-a-time style of programming" that came from the design of the von Neumann computer, and he proposed a functional style with an algebra of programs.9 Robin Milner's ML in the 1970s added type inference. Lazy languages such as Miranda led to Haskell, whose first report appeared in 1990. Hughes's paper "Why Functional Programming Matters" became the standard argument for the style.2 From the 2000s on, mainstream languages took lambdas, map and filter, immutable records and pattern matching from functional languages: C# added LINQ, Java added lambdas and streams, and Rust and Swift made immutable values the default.

References

  1. Functional Programming HOWTO, Python 3.14 documentation, Introduction
  2. Why Functional Programming Matters, John Hughes, The Computer Journal 32(2), 1989, 1 Introduction; 2 An Analogy with Structured Programming
  3. Array.prototype.reduce(), MDN Web Docs, Description
  4. Recursive Functions of Symbolic Expressions and Their Computation by Machine, Part I, John McCarthy, Communications of the ACM 3(4), 1960, 2 Functions and Function Definitions
  5. Haskell 2010 Language Report, Chapter 1 Introduction
  6. Concepts and terminology (functional transformation), .NET, Microsoft Learn, Pure functional transformations
  7. Package java.util.stream, Java SE 25 and JDK 25 API, package description; Stateless behaviors
  8. The Rust Programming Language, Functional Language Features: Iterators and Closures, Rust 1.99.1, chapter introduction
  9. Can Programming Be Liberated from the von Neumann Style? A Functional Style and Its Algebra of Programs, John Backus, Communications of the ACM 21(8), 1978, abstract; 11 Functional Programming Systems

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/WYHRGV/text.yaml