Conceptcore
Currying and partial application
Also called currying, partial application, curried function, uncurrying, bind, bind_front, functools.partial.
Currying turns a function of many arguments into a chain of functions of one argument. Partial application fixes some arguments of a function and returns a function of the rest.
- Applies to
- core-languages
Idea
A function of two arguments, such as power(base, exponent), can be seen as a function of one argument that returns a function of one argument. power(2) is then the function "two to the power of", and power(2)(10) is 1024. Currying is this change of form: a function of n arguments becomes a chain of n functions of one argument. Partial application is the related operation that fixes some arguments of a function and returns a function of the rest. The two ideas let a program make a specific function from a general one without writing a new definition:
from functools import partial
def power(base, exponent):
return base**exponent
square = partial(power, exponent=2)
print([square(n) for n in range(5)])
[0, 1, 4, 9, 16]
In ML, OCaml, F# and Haskell, functions are curried by default, and a call with fewer arguments is a partial application with no extra syntax. In most other languages, a closure or a library function does the same work.
How it works
One argument at a time. Christopher Strachey described the device in his lectures of 1967: "There is a device originated by Schönfinkel, for reducing operators with several operands to the successive application of single operand operators." Instead of +(2, p), a one-argument operator +′ gives +′(2), "a function which adds 2 to its argument". Strachey added a rule that application associates to the left, so +′ 2 p means (+′ 2) p.1 The Haskell report uses the same rule: "Function application is written e1 e2. Application associates to the left, so the parentheses may be omitted in (f x) y."2 So in Haskell, add 1 2 is the application of add 1 to 2, and add 1 alone is a function.
Types. The type of a curried function shows the chain. A function from two integers to an integer has the type Int -> Int -> Int, which means Int -> (Int -> Int). Uncurrying is the reverse change, to a function that takes a pair: (Int, Int) -> Int. The two types hold the same information, and a program can convert between them with two small higher-order functions, usually called curry and uncurry.
Partial application. Partial application fixes some arguments and leaves the rest open. It does not need the target function to be curried. The F# documentation states: "If you supply fewer than the specified number of arguments, you create a new function that expects the remaining arguments. This method of handling arguments is referred to as currying".3 In Python, functools.partial returns "a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords". Arguments in the later call are appended to the fixed ones.4 functools.Placeholder reserves a position, so that a later argument can fill a gap in the middle of the fixed arguments.5 In JavaScript, bind fixes the this value and leading arguments, which "are then inserted at the start of the arguments passed to the target function".6 In C++, std::bind_front and std::bind_back fix the first or the last arguments of a callable.7
Closures are the mechanism. A partially applied function must keep the fixed arguments until it is called. That is a closure: a function together with the values that it captured. In a language with closures, partial application is one line: b => f(a, b). In C, which has no closures, the program must store the function pointer and the fixed arguments in a struct. See closures.
When the arguments are evaluated. The fixed arguments are evaluated once, when the partial application is made. A closure that refers to a variable reads it when it runs. The difference matters in loops. A lambda made in a loop that reads the loop variable sees its last value, but partial(f, n) keeps the value of n at that point.
Argument order matters. Partial application of the leading arguments works best when the most general argument comes first. Libraries designed for currying put the data last, so that map(f) is a function that applies f to any list. Libraries designed for method calls put the data first, as the receiver.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Idiom | |
| C | Absent | |
| C# | Idiom | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | A lambda can return a lambda, and function types such as (Int) -> (Int) -> Int describe curried functions; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Absent | Functions in SQL are not values, so a query cannot fix some arguments of a function and pass the result on. Alternative: A view or a SQL function that calls another function with fixed arguments. |
| Bash | Idiom | |
| PowerShell | Idiom | A script block can call a function with fixed arguments, and GetNewClosure() captures the variables; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | HTML has no functions. |
| CSS | Does not apply | CSS has no functions that are values. |
| Regular expressions | Does not apply | A regular expression has no functions. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | functools.partial, closures |
| JavaScript | native | arrow functions, bind |
| TypeScript | native | as JavaScript, with generic types |
| Java | idiom | Function<A, Function<B, R>>, lambdas |
| Kotlin | idiom | lambdas that return lambdas |
| C# | idiom | Func<A, Func<B, R>>, lambdas |
| Go | idiom | closures, method values |
| Rust | idiom | closures with move, impl Fn |
| C | absent | a struct with a function pointer and the fixed arguments |
| C++ | stdlib | std::bind_front, std::bind_back, lambdas |
| Bash | idiom | a command prefix in an array, wrapper functions |
| PowerShell | idiom | script blocks |
| SQL | absent | functions are not values |
| Regex, HTML, CSS | n/a | no functions as values |
Python has functools.partial and partialmethod. Functions are not curried, and a call with too few arguments is a TypeError.
JavaScript and TypeScript curry with nested arrow functions, a => b => a + b, and partially apply with bind. A generic curry helper depends on the length of the function, which does not count rest parameters or parameters with default values.
Java and C# can express curried functions with nested function types and lambdas. Neither has a partial application function in the standard library.
Go returns closures. A method value, such as sb.WriteString, fixes the receiver of a method.
Rust returns closures with impl Fn. Each closure has its own anonymous type, so a collection of different closures needs Box<dyn Fn>.
C needs a struct for the fixed arguments. C++ has std::bind_front, std::bind_back and lambdas. std::bind and its placeholders are older and harder to read.
Bash stores a command and its first arguments in an array, or writes a small function that calls another one with a fixed first argument.
from functools import partial
def power(base, exponent):
return base**exponent
square = partial(power, exponent=2)
two_to = partial(power, 2)
print(square(5), two_to(10))
def curried_power(base):
def with_exponent(exponent):
return base**exponent
return with_exponent
print(curried_power(3)(2))
print(int("ff", 16), partial(int, base=16)("ff"))
25 1024
9
255 255
- Verdict: stdlib.
functools.partialreturns a new callable with some positional or keyword arguments fixed. Arguments in the later call are appended to the fixed positional arguments, and keyword arguments extend or override the fixed ones. - A curried function is a function that returns a function, and a closure is the usual way to write it. Python does not curry functions automatically.
functools.Placeholderreserves a position in the fixed arguments, so a later argument can fill a gap in the middle.
This code runs but gives a wrong answer on purpose.
adders = [lambda x: x + n for n in range(3)]
print([add(10) for add in adders])
[12, 12, 12]
Each lambda reads n when it is called, not when it is made, and at that time the loop has ended with n equal to 2. Fix the value at creation with partial(operator.add, n) or with a default argument, lambda x, n=n: x + n.
#include <functional>
#include <iostream>
#include <string>
int power(int base, int exponent) {
int r = 1;
for (int i = 0; i < exponent; ++i) r *= base;
return r;
}
int main() {
auto two_to = std::bind_front(power, 2);
auto add = [](int a) { return [a](int b) { return a + b; }; };
std::cout << two_to(10) << " " << add(1)(2) << "\n";
}
1024 3
- Verdict: stdlib.
std::bind_frontfixes the first arguments of a callable, andstd::bind_backfixes the last ones. A lambda that returns a lambda is a curried function. - The older
std::binduses placeholders such asstd::placeholders::_1. A lambda is usually clearer.
This code runs but gives a wrong answer on purpose.
#include <functional>
#include <iostream>
void add_to(int& total, int x) { total += x; }
int main() {
int total = 0;
auto add = std::bind_front(add_to, total);
add(5);
std::cout << total << "\n";
}
0
std::bind_front copies its arguments into the call wrapper. The call adds 5 to the copy, and total stays 0. Pass std::ref(total), or capture it by reference in a lambda.
import java.util.function.BiFunction;
import java.util.function.Function;
public class Main {
static <A, B, R> Function<B, R> partial(BiFunction<A, B, R> f, A a) {
return b -> f.apply(a, b);
}
public static void main(String[] args) {
Function<Integer, Function<Integer, Integer>> add = a -> b -> a + b;
Function<Integer, Integer> addTen = add.apply(10);
System.out.println(addTen.apply(5));
BiFunction<String, Integer, String> repeat = String::repeat;
Function<Integer, String> stars = partial(repeat, "*");
System.out.println(stars.apply(3));
}
}
15
***
- Verdict: idiom. A lambda can return a lambda, so
Function<A, Function<B, R>>is a curried function. The types are long, and each call isapply. - Java has no
partialin the standard library. A lambda that captures the fixed arguments does the same job. The captured local variables must be effectively final.
#include <stdio.h>
typedef int (*binary_fn)(int, int);
struct bound {
binary_fn f;
int first;
};
static int call_bound(struct bound b, int second) {
return b.f(b.first, second);
}
static int add(int a, int b) {
return a + b;
}
int main(void) {
struct bound add_ten = {add, 10};
printf("%d\n", call_bound(add_ten, 5));
return 0;
}
15
- Verdict: absent. C has function pointers but no closures, so a function cannot capture an argument. A struct that holds the function pointer and the fixed arguments is the usual replacement.
- Callback APIs in C, such as
pthread_createandqsort_r, take an extravoid *argument for the same reason.
Func<int, Func<int, int>> add = a => b => a + b;
var addTen = add(10);
Console.WriteLine(addTen(5));
static Func<B, R> Partial<A, B, R>(Func<A, B, R> f, A a) => b => f(a, b);
Func<string, int, string> pad = (s, width) => s.PadLeft(width, '.');
var padAbc = Partial(pad, "abc");
Console.WriteLine(padAbc(6));
15
...abc
- Verdict: idiom. Lambdas and the
Funcdelegate types can express curried functions and partial application. A helper such asPartialis a one-line generic method. - The standard library has no partial application helper.
const add = (a) => (b) => a + b;
const addTen = add(10);
console.log(addTen(5), add(1)(2));
function greet(greeting, name) {
return `${greeting}, ${name}`;
}
const hello = greet.bind(null, "hello");
console.log(hello("ann"));
const curry = (f) =>
function next(...args) {
return args.length >= f.length ? f(...args) : (...more) => next(...args, ...more);
};
const volume = curry((l, w, h) => l * w * h);
console.log(volume(2)(3)(4), volume(2, 3)(4), volume(2, 3, 4));
15 3
hello, ann
24 24 24
- Verdict: native. Arrow functions make curried functions short.
Function.prototype.bindfixes thethisvalue and any number of leading arguments. - A generic
curryhelper uses thelengthproperty of the function, the number of declared parameters. A rest parameter or a parameter with a default value is not counted, so such a helper fails for those functions.
This code runs but gives a wrong answer on purpose.
const add = (a) => (b) => a + b;
console.log(typeof add(1, 2));
function
add takes one argument and ignores the second. The call returns the inner function, not a number. A curried function must be called one argument at a time: add(1)(2).
function curry2<A, B, R>(f: (a: A, b: B) => R): (a: A) => (b: B) => R {
return (a) => (b) => f(a, b);
}
function partial<A, B, R>(f: (a: A, b: B) => R, a: A): (b: B) => R {
return (b) => f(a, b);
}
const repeat = (s: string, n: number): string => s.repeat(n);
const stars = curry2(repeat)("*");
const dashes = partial(repeat, "-");
console.log(stars(3), dashes(5));
*** -----
- Verdict: native. The rules are those of JavaScript. Generic helpers keep the types of the parameters and of the result, so the type checker rejects
stars("3"). - A generic
curryfor functions with any number of parameters needs variadic tuple types and conditional types, and its error messages are hard to read. Most code writes small closures.
package main
import (
"fmt"
"strings"
)
func add(a int) func(int) int {
return func(b int) int { return a + b }
}
func main() {
addTen := add(10)
fmt.Println(addTen(5), add(1)(2))
var sb strings.Builder
write := sb.WriteString
write("hello, ")
write("go")
fmt.Println(sb.String())
}
15 3
hello, go
- Verdict: idiom. A function can return a closure, so a curried function is easy to write. Go has no generic
partialin the standard library. - A method value such as
sb.WriteStringbinds the receiver. It is a partial application of the method to its receiver.
fn add(a: i32) -> impl Fn(i32) -> i32 {
move |b| a + b
}
fn partial<A: Copy, B, R>(f: impl Fn(A, B) -> R, a: A) -> impl Fn(B) -> R {
move |b| f(a, b)
}
fn main() {
let add_ten = add(10);
println!("{} {}", add_ten(5), add(1)(2));
let clamp_low = partial(i32::max, 0);
println!("{:?}", [-3, 4, -1].map(clamp_low));
}
15 3
[0, 4, 0]
- Verdict: idiom. A function can return a closure with
impl Fn. Themovekeyword moves the captured values into the closure, so the closure can outlive the function that made it. - Each closure has its own type. To store closures of different shapes together, use
Box<dyn Fn(i32) -> i32>.
search=(grep -c -i)
printf 'Error\nok\nERROR\n' > log.txt
"${search[@]}" error log.txt
log_with() {
local level=$1
shift
echo "[$level] $*"
}
warn() { log_with WARN "$@"; }
warn disk is full
2
[WARN] disk is full
- Verdict: idiom. A command and its first arguments can be stored in an array and run with more arguments. A small function that calls another function with a fixed first argument is a partial application.
- Shell functions are not values, so there is no closure and no curried function.
Variations and related ideas
- Automatic currying. In Haskell, OCaml and F#, each function takes one argument, and functions of many arguments are curried by default. In Scala, a method can have many parameter lists.
- Point-free style. With curried functions and composition, a function can be defined without naming its arguments:
sumSquares = sum . map (^2). The style is short, but it can be hard to read when it is overused. - Placeholders. Scala
_, C++std::placeholdersand Pythonfunctools.Placeholderfix arguments that are not at the start. - Method references and bound methods.
obj.methodin Python andsb.WriteStringin Go fix the receiver. See higher-order functions. - Default arguments. A default value fixes an argument for all callers. Partial application fixes it for one use.
Pitfalls
- Too many arguments in one call. In JavaScript,
add(1, 2)on a curriedaddignores the second argument and returns a function. - Late binding in loops. A closure made in a loop sees the last value of the loop variable. Partial application fixes the current value.
- Copies in C++.
std::bind_frontandstd::bindcopy their arguments. To bind a reference, usestd::ref. lengthin JavaScript. A genericcurryhelper calls the function too early when the function has rest parameters or default values.- Error messages. In a language that curries automatically, a missing argument does not cause an error at the call. The error appears later, where a function is used as if it were a value of another type.
- Readability. A chain of partial applications and compositions can hide what a function does. Name the intermediate functions.
Cost
A partially applied function is a closure, so making one allocates a small object in most languages. A call goes through one more level of indirection. Compilers for languages that curry by default, such as GHC and OCaml, optimize calls with all the arguments, so a curried function costs nothing extra when it gets all its arguments at once. In Rust and C++, each closure has its own type, and the compiler can inline the call completely. In Java and C#, a lambda that captures variables allocates an object, and a call through Function or Func is an interface or delegate call.
History
Moses Schönfinkel described the reduction of functions of several arguments to functions of one argument in his paper "Über die Bausteine der mathematischen Logik", published in 1924.1 Haskell Curry used the same device throughout combinatory logic, and the name currying comes from him. Christopher Strachey brought it into the theory of programming languages in his lectures of 1967.1 ML, in the 1970s, made curried functions the normal style, and Miranda, Haskell, OCaml and F# followed. Partial application came to other languages as a library feature: functools.partial in Python in 2006, Function.prototype.bind in ECMAScript 5 in 2009, and std::bind_front in C++20.
References
- Fundamental Concepts in Programming Languages, C. Strachey, lectures of 1967, Higher-Order and Symbolic Computation 13, 2000, 3.2.4 Evaluation
- Haskell 2010 Language Report, Expressions, 3.3 Curried Applications and Lambda Abstractions
- Functions, F# language reference, Microsoft Learn, Partial Application of Arguments
- functools, Python 3.14 documentation, functools.partial
- functools, Python 3.14 documentation, functools.Placeholder
- Function.prototype.bind(), MDN Web Docs, Partially applied functions
- std::bind_front, std::bind_back, cppreference.com, description
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag KJT04W Edit this page History Report an error Markdown