Conceptcore
Function type
Also called arrow type, function signature type, callable type, delegate type, functional interface, Func, std::function, fn pointer type, exponential type.
A function type is the type of a function value: its parameter types and its result type, as in int -> int. It lets a program pass, return and store functions.
- Applies to
- core-languages
Idea
A function can be a value: a program passes it to another function, returns it, or keeps it in a list. A value needs a type, and the type of a function says what it takes and what it gives back. The type of a function from an integer to an integer is written int -> int in many texts, Callable[[int], int] in Python, func(int) int in Go and Func<int, int> in C#. With function types, a compiler can check that a function passed as an argument has the right parameters and result.
from collections.abc import Callable
def twice(f: Callable[[int], int], x: int) -> int:
return f(f(x))
def inc(n: int) -> int:
return n + 1
def compose(f: Callable[[int], int], g: Callable[[int], int]) -> Callable[[int], int]:
return lambda x: f(g(x))
print(twice(inc, 5))
print(twice(lambda n: n * 3, 2))
h = compose(inc, lambda n: n * 10)
print(h(4), callable(h), type(h).__name__)
print(inc.__annotations__)
ops = {"+": lambda a, b: a + b, "*": lambda a, b: a * b}
print([op(6, 7) for op in ops.values()])
7
18
41 True function
{'n': <class 'int'>, 'return': <class 'int'>}
[13, 42]
twice takes a function of type Callable[[int], int] and calls it two times. compose takes two functions and returns a third one, so its result type is a function type too. A dictionary holds two functions of two parameters as values. The annotations record the parameter type and the result type of inc. Python does not check them when the program runs, but a type checker such as mypy does.
How it works
The type of a function value. "In computer science and mathematical logic, a function type (or arrow type or exponential) is the type of a variable or parameter to which a function has or can be assigned, or an argument or result type of a higher-order function taking or returning a function"1. "A function type depends on the type of the parameters and the result type of the function"1. In Go, "A function type denotes the set of all functions with the same parameter and result types"2.
The notations. The type theory notation is A -> B, a function from A to B. Haskell uses the same arrow. In Python, Callable[[int], str] "signifies a function that takes a single parameter of type int and returns a str"3. TypeScript writes a function type expression such as (a: string) => void, and these types "are syntactically similar to arrow functions"4. Go writes func(int) string, Rust writes fn(i32) -> String, and C writes a pointer to a function as int (*)(int). C++ has function types such as int(int) and the wrapper std::function<int(int)>.
Structural and nominal function types. In Go, Rust, TypeScript and Python, the parameter and result types decide the function type. Go says that "Two function types are identical if they have the same number of parameters and result values, corresponding parameter and result types are identical, and either both functions are variadic or neither is", and "Parameter and result names are not required to match"2. Java has no arrow type. It uses interfaces with one method: "Functional interfaces provide target types for lambda expressions and method references. Each functional interface has a single abstract method"5. Thus Function<Integer, Integer> and IntUnaryOperator are two types for the same lambda. C# uses delegate types in the same way: Func<T, TResult> "Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter"6.
One type for each function. Rust and C++ give each function or closure a type of its own, so that the compiler knows the exact function at each call. In Rust, a function item "yields a zero-sized value of its function item type", so "no indirection is needed when the function is called"7. "A closure expression produces a closure value with a unique, anonymous type that cannot be written out"8. In C++, a lambda has a "unique unnamed non-union non-aggregate class type, known as closure type"9. To keep different functions in one variable or one list, a program uses a common type: "A function pointer type, written using the fn keyword, refers to a function whose identity is not necessarily known at compile-time"10. In C++, std::function "is a general-purpose polymorphic function wrapper"11. In C, "A pointer to function can be initialized with an address of a function"12.
Subtyping of function types. A function that accepts any animal can stand in where a function that accepts cats is expected, but not the other way. "In other words, the → type constructor is contravariant in the parameter (input) type and covariant in the return (output) type"13. TypeScript checks this rule only with a flag: with strictFunctionTypes, "this flag causes functions parameters to be checked more correctly"14. See subtyping.
Function types as values. A language with function types can treat functions as first-class functions: it can pass them to higher-order functions, return them, and store them. A closure is a function value that also holds the variables that it captured. Its function type shows only the parameters and the result, not the captured variables.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript writes function types as function type expressions, which look like arrow functions, and as call signatures in object types. A function with fewer parameters fits a type with more parameters. No example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has function types such as (Int) -> String and Int.() -> Unit, and lambdas and function references have these types. On the JVM, they compile to the interfaces Function0, Function1 and so on. No example file exists because kotlinc is not installed. |
| SQL | Absent | Standard SQL has functions, but they are not values, so a query cannot pass a function to another function or store one in a column. No example file exists. |
| Bash | Idiom | A Bash function is a command, not a value. A script passes the name of a function as a string and calls it with "$f" args, and there are no parameter or result types. No example file exists. |
| PowerShell | Native | A script block such as { param($x) $x + 1 } is a value that a script stores, passes and calls with & or .Invoke(). PowerShell also converts script blocks to .NET delegate types such as [Func[int,int]]. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no functions. An event handler attribute such as onclick holds JavaScript code, and the function type belongs to JavaScript. |
| CSS | Does not apply | CSS uses functional notation such as calc(), rgb() and var(), but these are fixed parts of the value syntax, not function values that a style sheet passes around. |
| Regular expressions | Does not apply | A regular expression has no functions and no function values. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | functions are objects; Callable[[int], str] in annotations, which type checkers read |
| JavaScript | native | functions are objects, and typeof gives "function"; no parameter types |
| TypeScript | native | function type expressions such as (a: string) => void; call signatures |
| Java | native | functional interfaces such as Function<T, R>; a lambda takes the type that the context expects |
| Kotlin | native | function types such as (Int) -> String; lambdas and function references |
| C# | native | delegate types such as Func<T, TResult> and Action<T> |
| Go | native | function types such as func(int) int; a function value compares only with nil |
| Rust | native | fn(i32) -> i32 pointers; a unique type for each function and closure; the traits Fn, FnMut and FnOnce |
| C | native | function types and pointers to functions such as int (*)(int) |
| C++ | native | function types and pointers; a unique type for each lambda; std::function<int(int)> |
| Bash | idiom | a function is a command, not a value; a script passes the name of a function as a string |
| PowerShell | native | script blocks such as { param($x) $x + 1 } and .NET delegates such as [Func[int,int]] |
| SQL | absent | functions are not values, so a query cannot pass a function to a function |
| Regex | n/a | a pattern has no functions |
| HTML | n/a | HTML has no functions; event handler attributes hold JavaScript code |
| CSS | n/a | calc() and rgb() use functional notation, but they are not function values |
The general-purpose languages all have function values, so the verdict is native for them except Bash. They differ in whether a function type is structural, as func(int) int in Go, or nominal, as the functional interfaces of Java and the delegates of C#, and in whether each function has a type of its own, as in Rust and C++.
The example files show these differences. Python shows that annotations are not checked when the program runs, that an object with __call__ is callable, and that lambdas in a loop read the loop variable late. JavaScript shows that any function fits any call, which gives [1, NaN, NaN] from map(parseInt). Java shows Function, IntUnaryOperator, BiFunction, Supplier, compose and a method reference. C# shows Func and Action, a method group and the type of a lambda with var. Go shows a named function type, strings.Map with a function argument, and a comparison with nil. Rust shows that a function item has the size 0, a closure as a generic parameter, Box<dyn Fn> for a list of closures, and the conversion of a closure to a fn pointer. C uses an array of function pointers and qsort. C++ shows that two equal lambdas have different types, a list of std::function values and the exception of an empty std::function.
import inspect
from collections.abc import Callable
def apply(f: Callable[[int], int], x: int) -> int:
return f(x)
# Annotations are not checked when the program runs, so a str function runs too.
print(apply(str.upper, "abc"))
# An object with __call__ is callable, so it fits Callable.
class Scale:
def __init__(self, k):
self.k = k
def __call__(self, n):
return n * self.k
print(apply(Scale(3), 5), callable(Scale(3)), callable(5))
print(inspect.signature(apply))
# Each lambda reads i when it runs, not when it is made.
fs = [lambda: i for i in range(3)]
print([f() for f in fs])
fs = [lambda i=i: i for i in range(3)]
print([f() for f in fs])
ABC
15 True False
(f: collections.abc.Callable[[int], int], x: int) -> int
[2, 2, 2]
[0, 1, 2]
- Verdict: native. A function is an object, and
Callable[[int], int]describes it for a type checker. The interpreter does not check the annotation, soapply(str.upper, "abc")runs. Any object with a__call__method is callable. The lambdas in the first list all readiafter the loop ends, so they return 2. A default argument stores the value ofiwhen each lambda is made.
#include <functional>
#include <iostream>
#include <type_traits>
#include <vector>
int inc(int n) { return n + 1; }
int twice(int (*f)(int), int x) { return f(f(x)); }
int main() {
std::cout << twice(inc, 5) << '\n';
// Each lambda has its own closure type.
auto a = [](int n) { return n * 2; };
auto b = [](int n) { return n * 2; };
std::cout << std::is_same_v<decltype(a), decltype(b)> << '\n';
// std::function holds any callable with a matching signature.
int k = 10;
std::vector<std::function<int(int)>> ops{inc, a, [k](int n) { return n + k; }};
for (const auto& f : ops) {
std::cout << f(3) << '\n';
}
// A lambda without captures converts to a function pointer.
std::cout << twice(a, 3) << '\n';
std::function<int(int)> empty;
try {
empty(1);
} catch (const std::bad_function_call&) {
std::cout << "bad_function_call\n";
}
}
7
0
4
6
13
12
bad_function_call
- Verdict: native.
int (*)(int)is a function pointer type, andint(int)is the function type insidestd::function<int(int)>. Two lambdas with the same text have two closure types, sois_same_vgives 0. Astd::vectorofstd::functionholds a function, a lambda and a lambda with a capture. A lambda without captures converts to a function pointer. A call to an emptystd::functionthrowsstd::bad_function_call.
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.Supplier;
public class Main {
static int twice(IntUnaryOperator f, int x) {
return f.applyAsInt(f.applyAsInt(x));
}
public static void main(String[] args) {
Function<Integer, Integer> inc = n -> n + 1;
IntUnaryOperator incInt = n -> n + 1;
System.out.println(inc.apply(5) + " " + twice(incInt, 5));
Function<Integer, Integer> times10 = n -> n * 10;
Function<Integer, Integer> both = inc.compose(times10);
System.out.println(both.apply(4));
BiFunction<String, Integer, String> repeat = String::repeat;
Supplier<String> hello = () -> "hello";
System.out.println(repeat.apply("ab", 3) + " " + hello.get());
// A Function is not an IntUnaryOperator, so a method reference converts it.
IntUnaryOperator fromInc = inc::apply;
System.out.println(twice(fromInc, 1));
}
}
6 7
41
ababab hello
3
- Verdict: native. Java has no arrow type. A lambda or a method reference takes the type of the functional interface that the context expects, such as
Function<Integer, Integer>,IntUnaryOperator,BiFunctionorSupplier.inc.compose(times10)runstimes10first, so the result for 4 is 41.inccannot go totwicedirectly, because its type isFunction, but the method referenceinc::applymakes anIntUnaryOperatorfrom it.
#include <stdio.h>
#include <stdlib.h>
typedef int (*int_op)(int);
static int inc(int n) { return n + 1; }
static int square(int n) { return n * n; }
static int twice(int (*f)(int), int x) { return f(f(x)); }
static int compare_ints(const void *a, const void *b) {
int x = *(const int *)a;
int y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void) {
printf("%d %d\n", twice(inc, 5), twice(&square, 3));
int_op ops[] = { inc, square };
for (size_t i = 0; i < sizeof ops / sizeof ops[0]; i++) {
printf("%d\n", ops[i](4));
}
/* qsort takes a pointer to a comparison function. */
int a[] = { 3, 1, 2 };
qsort(a, 3, sizeof a[0], compare_ints);
printf("%d %d %d\n", a[0], a[1], a[2]);
return 0;
}
7 81
5
16
1 2 3
- Verdict: native.
int (*)(int)is a pointer to a function that takes anintand returns anint, and atypedefgives it a short name. A function name converts to a pointer, soincand&squareboth work. An array of function pointers holds several functions.qsorttakes a comparison function of the typeint (*)(const void *, const void *), so the comparison has to convert the pointers itself.
using System;
using System.Linq;
Func<int, int> inc = n => n + 1;
Func<Func<int, int>, int, int> twice = (f, x) => f(f(x));
Console.WriteLine(twice(inc, 5));
// A method group converts to a delegate type.
Func<string, int> parse = int.Parse;
Console.WriteLine(new[] { "1", "2", "3" }.Select(parse).Sum());
// Action is the delegate type for a function with no result.
Action<string> say = s => Console.WriteLine("say " + s);
say("hi");
// A lambda with var gets a Func or Action type.
var square = (int n) => n * n;
Console.WriteLine(square.GetType().Name + " " + square(7));
// A function returns a function.
Func<int, Func<int, int>> adder = a => b => a + b;
Console.WriteLine(adder(10)(5));
7
6
say hi
Func`2 49
15
- Verdict: native.
Func<T, TResult>andAction<T>are delegate types from the library, and a lambda or a method group such asint.Parseconverts to them.twicetakes a delegate as a parameter, so its type isFunc<Func<int, int>, int, int>. Withvar, the compiler gives the lambda a natural type, hereFunc`2, which isFunc<int, int>.
const inc = (n) => n + 1;
function twice(f, x) {
return f(f(x));
}
console.log(typeof inc, inc.length, twice(inc, 5));
// A function has no parameter types, so any function fits any call.
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
// A function returns a function.
const adder = (a) => (b) => a + b;
const add10 = adder(10);
console.log(add10(5), adder(1)(2));
// Extra arguments are ignored, and missing arguments are undefined.
const show = (a, b) => `${a} ${b}`;
console.log(show(1, 2, 3), show(1));
function 1 7
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
15 3
1 2 1 undefined
- Verdict: native. A function is an object,
typeofgives"function", andlengthgives the number of declared parameters. JavaScript does not check the number of arguments, somappasses the element and the index toparseInt, and the index becomes the radix. A wrapper that passes only the element gives the expected result.adderreturns a function, so its result has a function type.
package main
import (
"fmt"
"strings"
)
type IntOp func(int) int
func twice(f func(int) int, x int) int {
return f(f(x))
}
func adder(a int) func(int) int {
return func(b int) int { return a + b }
}
func main() {
inc := func(n int) int { return n + 1 }
fmt.Println(twice(inc, 5))
fmt.Printf("%T\n", inc)
// IntOp and func(int) int have the same underlying type, so the values are assignable.
var op IntOp = inc
fmt.Println(twice(op, 1))
fmt.Println(strings.Map(func(r rune) rune { return r + 1 }, "HAL"))
fmt.Println(adder(10)(5))
// A function value compares only with nil.
var f func(int) int
fmt.Println(f == nil, inc != nil)
}
7
func(int) int
3
IBM
15
true true
- Verdict: native.
func(int) intis a function type, and%Tprints it. A named type such asIntOphas the same underlying type, so a value moves between the two types without a conversion.strings.Maptakes a function fromrunetorune. The zero value of a function type isnil, and==works only withnil.
fn inc(n: i32) -> i32 {
n + 1
}
fn twice(f: fn(i32) -> i32, x: i32) -> i32 {
f(f(x))
}
fn apply<F: Fn(i32) -> i32>(f: F, x: i32) -> i32 {
f(x)
}
fn adder(a: i32) -> impl Fn(i32) -> i32 {
move |b| a + b
}
fn main() {
println!("{} {}", twice(inc, 5), std::mem::size_of_val(&inc));
let k = 10;
let add_k = |n: i32| n + k;
println!("{}", apply(add_k, 1));
// Each closure has its own type, so a Vec of closures needs Box<dyn Fn>.
let ops: Vec<Box<dyn Fn(i32) -> i32>> = vec![Box::new(inc), Box::new(add_k), Box::new(|n| n * n)];
println!("{:?}", ops.iter().map(|f| f(3)).collect::<Vec<_>>());
// A closure that captures nothing converts to a fn pointer.
let square: fn(i32) -> i32 = |n| n * n;
println!("{} {}", twice(square, 3), adder(10)(5));
}
7 0
11
[4, 13, 9]
81 15
- Verdict: native. The value
inchas a function item type of size 0, and it converts to the pointer typefn(i32) -> i32whentwiceneeds one. A generic parameter with the boundFn(i32) -> i32accepts any closure, and the compiler makes a copy ofapplyfor each closure type.Box<dyn Fn(i32) -> i32>gives three different functions one type. A closure that captures nothing converts to afnpointer.
Variations and related ideas
- Curried function types.
int -> int -> intis a function that takes anintand returns a function frominttoint. Haskell and ML define functions of many parameters in this way. See currying. - Function pointers and delegates. A function pointer holds only the address of a function. A delegate or a function object can also hold an object or captured variables. See function pointer and delegate and function object.
- Effects in the type. Java lists checked exceptions in a method signature, and Rust
FnOnce,FnMutandFnsay whether a closure can run once, can change its captures, or only reads them. - Generic function types.
<T>(x: T) => Tin TypeScript andfn<T>(T) -> Tas a generic function in Rust are types of functions that work for eachT. See parametric polymorphism. - Composite types. A function type is a composite type: a type constructor builds it from the parameter types and the result type.
Pitfalls
- A callback that gets more arguments than it expects. In JavaScript,
['1', '2', '3'].map(parseInt)gives[1, NaN, NaN], becausemap"passes 3 arguments: the element, the index, and the array"15, andparseIntuses the second one as the radix. Wrap the function:map((s) => parseInt(s, 10)). TypeScript does not catch this, because "Functions with fewer parameters (of the same types) can always take the place of functions with more parameters"4. - Method syntax is not checked strictly.
strictFunctionTypes"only applies to functions written in function syntax, not to those in method syntax"14. A property declared asf(x: string | number): voidaccepts a function that takes only astring, and a call with a number then fails. - An empty function value. In Go, "The value of an uninitialized variable of function type is nil"2, and "Calling a nil function value causes a run-time panic"2. In C++, "Invoking the target of an empty std::function results in std::bad_function_call exception being thrown"11. Check for an empty value before the call, or give the variable a default function.
- Two function types with the same signature. In Java, a
Function<Integer, Integer>is not anIntUnaryOperator, and in C#, aFunc<int, int>is not a delegate type of your own with the same signature. Convert with a method reference or a lambda, such asinc::apply. - A list of closures. In Rust and C++, two closures have two types, so they cannot share a list without a common type such as
Box<dyn Fn(i32) -> i32>orstd::function<int(int)>.
Cost
A call to a known function is a direct call, and the compiler can inline it. A call through a function value is an indirect call: the program loads an address and jumps to it, and the compiler usually cannot inline it. Rust and C++ give each closure its own type, so a generic function that takes the closure type gets a copy for each closure and can inline the call. A common type such as std::function or Box<dyn Fn> stores the closure behind a pointer and adds an indirect call. In Java and C#, a lambda is an object, and a call goes through the method of the interface or the delegate.
History
Function types come from logic. "The simply typed lambda calculus was originally introduced by Alonzo Church in 1940 as an attempt to avoid paradoxical use of the untyped lambda calculus"16. It has "only one type constructor" and that constructor "builds function types"16. Church wrote types as subscripts, and "By the 1970s stand-alone arrow notation was in use"16. The rule that function types are contravariant in the parameter type "was first stated formally by John C. Reynolds"13, and a paper by Luca Cardelli made it better known13.
References
- Function type, Wikipedia, Introduction; Programming languages
- The Go Programming Language Specification, Function types; Type identity; Comparison operators; Calls
- typing, Python 3.14 documentation, Annotating callable objects
- More on Functions, The TypeScript Handbook, Function Type Expressions; Optional Parameters in Callbacks
- Java SE 25 API, Package java.util.function, Package description
- Func<T,TResult> Delegate, .NET API reference, Definition
- Function item types, The Rust Reference, Introduction
- Closure types, The Rust Reference, Introduction
- Lambda expressions, C++ reference, cppreference.com, Closure type
- Function pointer types, The Rust Reference, Introduction
- std::function, C++ reference, cppreference.com, Description
- Pointer declaration, C reference, cppreference.com, Pointers to functions
- Covariance and contravariance (computer science), Wikipedia, Function types
- TSConfig Option strictFunctionTypes, TypeScript documentation, Description
- Array.prototype.map(), MDN Web Docs, Using parseInt() with map()
- Simply typed lambda calculus, Wikipedia, Introduction; Syntax
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 RWHYVY Edit this page History Report an error Markdown