Conceptadvanced
Function object
Also called functor, callable object, function-like object, invocable object.
A function object is an object that a program can call like a function. It can keep state between calls. Examples are C++ classes with operator(), Python classes with __call__ and Rust closures.
- Applies to
- core-languages
Idea
A function object is an object that the program can call with the syntax of a function call. Wikipedia describes a function object as "a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax"1. "In some languages, particularly C++, function objects are often called functors (not related to the functional programming concept)."1
A function object is an object, so it has fields. It can keep data from one call to the next call.
class Multiplier:
def __init__(self, factor):
self.factor = factor
self.calls = 0
def __call__(self, x):
self.calls += 1
return x * self.factor
triple = Multiplier(3)
print(triple(5))
print(list(map(triple, [1, 2, 3])))
print(triple.calls)
15
[3, 6, 9]
4
triple is an object of the class Multiplier. The call triple(5) runs the method __call__. map takes triple as it takes any function. The field calls counts the four calls.
How it works
- A call operator on the type. The type defines what a call does. In Python,
__call__is "Called when the instance is “called” as a function"2. In C++, "When a user-defined class overloads the function call operator operator(), it becomes a FunctionObject type."3 - The call. A call
f(x)on an object runs that method with the object as the receiver. Python says thatx(arg1, arg2, ...)"roughly translates to type(x).call(x, arg1, ...)"2. - The state. The fields of the object hold the data that the function needs. Wikipedia says that "Another advantage of function objects is their ability to maintain a state that affects operator() between calls."1
- Use as a function. Code that takes a function can take the object. In C++, "A FunctionObject type is the type of an object that can be used on the left of the function call operator."4
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Idiom | |
| C | Idiom | |
| C# | Idiom | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Idiom | |
| Rust | Native | |
| Kotlin | Native | A Kotlin class can declare an operator fun invoke, and then a program calls its objects like functions. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL has no objects that a query can call. |
| Bash | Absent | |
| PowerShell | Idiom | A PowerShell script block is a value that a program calls with the & operator, and the GetNewClosure method binds it to variables. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no functions or objects. |
| CSS | Does not apply | CSS has no objects that a style sheet can call. |
| Regular expressions | Does not apply | A regular expression has no functions or objects. |
- Python. Any class with a
__call__method. "Instances of arbitrary classes can be made callable by defining a call() method in their class."2 Functions, methods and classes are callable too: "Classes are callable."2 - C++. A class with
operator()3. A lambda is a function object of a class that the compiler makes, "known as closure type"5.std::functioncan hold any function object with the right signature6. - Rust. A closure is a function object. The traits
Fn,FnMutandFnOncedescribe how it uses its captured data.Fnis "The version of the call operator that takes an immutable receiver."7 "FnMut applies to closures that don’t move captured values out of their body but might mutate the captured values."8 - Java. An object of a class that implements a functional interface. "Java has no first-class functions, so function objects are usually expressed by an interface with a single method"1. For example,
IntUnaryOperator"Represents an operation on a single int-valued operand that produces an int-valued result."9 The caller calls the method of the interface by its name. - C#. A delegate for an instance method is a function object. "When a delegate is constructed to wrap an instance method, the delegate references both the instance and the method."10
- JavaScript. "In JavaScript, every function is actually a Function object."11 A function can have properties, so a function is already a function object.
- TypeScript. A call signature in an object type describes a function with properties. "If we want to describe something callable with properties, we can write a call signature in an object type"12.
- Go. Go has no call operator on objects. A method value
x.Mgives a function: "The method value x.M is a function value that is callable with the same arguments as a method call of x.M."13 Go also goes the other way. A function type can have methods, as inhttp.HandlerFunc: "If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f."14 - C. C has no function objects. A struct holds the data, and a function takes a pointer to the struct.
- Bash. Bash has no objects. A function keeps data between calls in global variables.
class Multiplier:
def __init__(self, factor):
self.factor = factor
self.calls = 0
def __call__(self, x):
self.calls += 1
return x * self.factor
triple = Multiplier(3)
print(triple(5))
print(" ".join(str(y) for y in map(triple, [1, 2, 3])))
print(triple.calls)
15
3 6 9
4
- Verdict: native. The method
__call__makes an object of the class callable.maptakes the object as it takes a function, and the fieldcallskeeps the count between calls.
#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>
struct Multiplier {
int factor;
int calls = 0;
int operator()(int x) {
++calls;
return x * factor;
}
};
int main() {
Multiplier triple{3};
std::cout << triple(5) << '\n';
std::vector<int> xs = {1, 2, 3};
std::vector<int> out(xs.size());
std::transform(xs.begin(), xs.end(), out.begin(), std::ref(triple));
for (std::size_t i = 0; i < out.size(); ++i) {
std::cout << (i ? " " : "") << out[i];
}
std::cout << '\n';
std::cout << triple.calls << '\n';
}
15
3 6 9
4
- Verdict: native. The struct overloads
operator(), sotriple(5)is a call.std::transformtakes its function object by value, so the program passesstd::ref(triple)to keep the count intripleand not in a copy.
import java.util.function.IntUnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
static class Multiplier implements IntUnaryOperator {
private final int factor;
int calls = 0;
Multiplier(int factor) {
this.factor = factor;
}
@Override
public int applyAsInt(int x) {
calls++;
return x * factor;
}
}
public static void main(String[] args) {
Multiplier triple = new Multiplier(3);
System.out.println(triple.applyAsInt(5));
String out = IntStream.of(1, 2, 3)
.map(triple)
.mapToObj(String::valueOf)
.collect(Collectors.joining(" "));
System.out.println(out);
System.out.println(triple.calls);
}
}
15
3 6 9
4
- Verdict: idiom. Java has no call operator for objects. The class implements the functional interface
IntUnaryOperator, soIntStream.maptakes the object. A direct call uses the name of the method,applyAsInt.
#include <stdio.h>
struct multiplier {
int factor;
int calls;
};
static int multiply(void *ctx, int x) {
struct multiplier *m = ctx;
m->calls++;
return x * m->factor;
}
static void map_ints(int (*f)(void *, int), void *ctx, const int *xs, int *out, int n) {
for (int i = 0; i < n; i++) {
out[i] = f(ctx, xs[i]);
}
}
int main(void) {
struct multiplier triple = {3, 0};
printf("%d\n", multiply(&triple, 5));
int xs[] = {1, 2, 3};
int out[3];
map_ints(multiply, &triple, xs, out, 3);
printf("%d %d %d\n", out[0], out[1], out[2]);
printf("%d\n", triple.calls);
return 0;
}
15
3 6 9
4
- Verdict: idiom. C has no function objects. The struct holds the data, and the program passes a function pointer and a pointer to the struct together.
map_intsgives the struct to each call.
using System;
using System.Linq;
class Multiplier
{
private readonly int factor;
public int Calls;
public Multiplier(int factor)
{
this.factor = factor;
}
public int Apply(int x)
{
Calls++;
return x * factor;
}
}
class Program
{
static void Main()
{
var triple = new Multiplier(3);
Func<int, int> f = triple.Apply;
Console.WriteLine(f(5));
Console.WriteLine(string.Join(" ", new[] { 1, 2, 3 }.Select(f)));
Console.WriteLine(triple.Calls);
}
}
15
3 6 9
4
- Verdict: idiom. A C# class cannot overload the call operator. The delegate
fwraps the instance methodApply, so it holds the objecttripleand the method. Each call throughfchanges the fieldCallsof that object.
function makeMultiplier(factor) {
function multiply(x) {
multiply.calls += 1;
return x * factor;
}
multiply.calls = 0;
return multiply;
}
const triple = makeMultiplier(3);
console.log(triple(5));
console.log([1, 2, 3].map((x) => triple(x)).join(" "));
console.log(triple.calls);
15
3 6 9
4
- Verdict: native. A JavaScript function is an object, so it can have properties. The function
multiplykeeps the count in its own propertycalls.
type Multiplier = {
(x: number): number;
calls: number;
};
function makeMultiplier(factor: number): Multiplier {
const multiply: Multiplier = Object.assign(
(x: number): number => {
multiply.calls += 1;
return x * factor;
},
{ calls: 0 },
);
return multiply;
}
const triple = makeMultiplier(3);
console.log(triple(5));
console.log([1, 2, 3].map((x) => triple(x)).join(" "));
console.log(triple.calls);
15
3 6 9
4
- Verdict: native. The type
Multiplierhas a call signature and a property, so it describes a function that is also an object with a field.Object.assignadds the propertycallsto the arrow function.
package main
import (
"fmt"
"strconv"
"strings"
)
type Multiplier struct {
factor int
calls int
}
func (m *Multiplier) Apply(x int) int {
m.calls++
return x * m.factor
}
func mapInts(f func(int) int, xs []int) []string {
out := make([]string, 0, len(xs))
for _, x := range xs {
out = append(out, strconv.Itoa(f(x)))
}
return out
}
func main() {
triple := &Multiplier{factor: 3}
f := triple.Apply
fmt.Println(f(5))
fmt.Println(strings.Join(mapInts(f, []int{1, 2, 3}), " "))
fmt.Println(triple.calls)
}
15
3 6 9
4
- Verdict: idiom. Go has no call operator for structs. The method value
triple.Applyis a function value that keeps the pointertriple, so each call changes the fieldcalls.
fn main() {
let factor = 3;
let mut calls = 0;
let mut triple = |x: i32| {
calls += 1;
x * factor
};
println!("{}", triple(5));
let out: Vec<String> = [1, 2, 3].iter().map(|&x| triple(x).to_string()).collect();
println!("{}", out.join(" "));
println!("{}", calls);
}
15
3 6 9
4
- Verdict: native. A Rust closure is a function object that the compiler makes. This closure changes the captured variable
calls, so it implementsFnMutand the bindingtriplemust bemut.
factor=3
calls=0
triple() {
calls=$((calls + 1))
result=$(($1 * factor))
}
triple 5
echo "$result"
out=()
for x in 1 2 3; do
triple "$x"
out+=("$result")
done
echo "${out[*]}"
echo "$calls"
15
3 6 9
4
- Verdict: absent. Bash has no objects. The function keeps its data in the global variables
factorandcallsand gives its result inresult. A command substitution such as$(triple 5)runs in a subshell, and the change tocallswould be lost.
Variations and related ideas
- Closures. A closure and a function object both join code and data. "Many uses of functors in languages like C++ are simply emulations of the missing closure constructor."1 A C++ lambda is a function object with the captured variables as its fields5. See Closure.
- Function pointers. A function pointer has no data. "A callback in procedural languages, such as C, may be performed by using function pointers."1 "However it can be difficult or awkward to pass a state into or out of the callback function."1 See Function pointers and delegates.
- Single-method interfaces. Java uses an interface with one method in place of a call operator19.
- Function to object. Go
http.HandlerFuncturns a function into a value of an interface type14.
Pitfalls
A C++ algorithm works on a copy
The C++ algorithms take the function object by value. std::for_each is declared as UnaryFunc for_each( InputIt first, InputIt last, UnaryFunc f );15, so it changes a copy of the object:
This code runs but gives a wrong answer on purpose.
#include <algorithm>
#include <iostream>
#include <vector>
struct Counter {
int calls = 0;
void operator()(int) { ++calls; }
};
int main() {
std::vector<int> v = {1, 2, 3};
Counter c;
std::for_each(v.begin(), v.end(), c);
std::cout << c.calls << '\n';
}
0
The copy counted 3 calls, and the program dropped it. std::for_each returns the copy: its return value is f15. Write c = std::for_each(v.begin(), v.end(), c);, and c.calls is 3.
A mutating closure is not an Fn in Rust
A Rust closure that changes a captured variable implements FnMut but not Fn8. A function with an Fn bound does not accept it. Fn is for code that will "call it repeatedly and without mutating state (e.g., when calling it concurrently)"7. The same page says: "If you do not need such strict requirements, use FnMut or FnOnce as bounds."7
Cost
A call to a function object is a call to a method. When the compiler knows the type of the object, it knows which method runs. Wikipedia notes for D that function objects in the C++ style exist "To allow the compiler to inline the code"1. A C++ std::function is "a general-purpose polymorphic function wrapper"6, so one type holds targets of many types.
References
- Function object, Wikipedia, the introduction; Description; In C++, Maintaining state; In Java; In D
- Data model, The Python Language Reference, 3.2.8 Callable types; 3.3.6 Emulating callable objects
- Operator overloading, C++ reference, cppreference.com, Function call operator
- C++ named requirements, FunctionObject, cppreference.com, the introduction
- Lambda expressions, C++ reference, cppreference.com, Closure type
- std::function, C++ reference, cppreference.com, the introduction
- Trait Fn, The Rust Standard Library, the description
- Closures, The Rust Programming Language, Moving Captured Values Out of Closures and the Fn Traits
- Package java.util.function, Java SE 25 API, the package description
- Using Delegates, C# Programming Guide, the whole page
- Function, MDN Web Docs, the introduction
- More on Functions, The TypeScript Handbook, Call Signatures
- The Go Programming Language Specification, Method values
- Package http, Go standard library, type HandlerFunc
- std::for_each, C++ reference, cppreference.com, the declaration; Return value
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 | W2 basic |
|
Tag TAEWCN Edit this page History Report an error Markdown