Conceptintro
First-class function
Also called first-class functions, functions as values, function value, first-class procedure.
A language has first-class functions when a function is a value. A program can store a function in a variable, pass it as an argument, return it from a function and put it in a data structure.
- Applies to
- core-languages
Idea
A language has first-class functions when a function is a value, as a number or a string is a value. Wikipedia gives the definition: "In computer science, a programming language is said to have first-class functions if it treats functions as first-class citizens."1
Structure and Interpretation of Computer Programs lists four rights of a first-class element2:
- "They may be named by variables."
- "They may be passed as arguments to procedures."
- "They may be returned as the results of procedures."
- "They may be included in data structures."
MDN says the same for JavaScript: "a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable."3
def double(x):
return x * 2
def square(x):
return x * x
for f in [double, square, abs]:
print(f.__name__, f(-3))
double -6
square 9
abs 3
The list holds three functions, two defined in the program and one built in. The loop takes each function from the list, puts it in the variable f and calls it.
How it works
- A function is an object. The definition of a function makes a value and gives it a name. In Python, "A function definition associates the function name with the function object in the current symbol table."4
- Store it. An assignment copies the value to a second name. Python says that "Other names can also point to that same function object and can also be used to access the function"4.
- Call it through any name. A call needs a value that can be called, not a fixed name. In Python, "The primary must evaluate to a callable object"5. So
f(5),ops["square"](4)anddouble(5)are all calls. - Pass it and return it. A function that takes or returns a function is a higher-order function.
- Keep the free variables. A function made inside another function can use the local variables of the outer function. These variables must stay alive after the outer function returns. This makes the function value a closure.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has function types such as (Int) -> Int, lambdas and function references such as ::double. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | Standard SQL has no function values. A query calls functions by name. |
| Bash | Idiom | |
| PowerShell | Idiom | A PowerShell function is a command and not a value, but a script block is a value. A program stores a script block in a variable and calls it with the & operator. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is a markup language and has no functions. Event handler attributes hold JavaScript code. |
| CSS | Does not apply | CSS has functions such as calc(), but they are not values that a style sheet can store or pass. |
| Regular expressions | Does not apply | A regular expression has no functions. |
- Python. Functions are objects.
defmakes a function object and gives it a name4. "Small anonymous functions can be created with the lambda keyword."4 - JavaScript. Functions are values. MDN says that functions "are treated like any other variable"3.
- TypeScript. The handbook says that functions are "also values"6. A function type expression such as
(a: string) => voidgives the type of a function value6. - Java. A method is not a value, but a lambda expression or a method reference is. Lambda expressions "treat functionality as method argument, or code as data"7. The type of the value is a functional interface: "Functional interfaces provide target types for lambda expressions and method references."8
- C#. A delegate holds a function: "A delegate is a type that represents references to methods with a particular parameter list and return type."9 "Delegates allow methods to be passed as parameters."9 A lambda converts to a delegate type such as
Func<int, int>10. - C. A function is not a value, but a pointer to a function is: "Unlike functions, pointers to functions are objects and thus can be stored in arrays, copied, assigned, passed to other functions as arguments, etc."11 C cannot make a new function at run time. "There are no nested functions"12, so a C program keeps extra data in a struct and passes it with the pointer.
- C++. C++ has function pointers from C, and lambdas. A lambda "Constructs a closure (an unnamed function object capable of capturing variables in scope)."13
std::functioncan hold any of them: "Class template std::function is a general-purpose polymorphic function wrapper."14 - Go. Functions are values with a function type. "A function type denotes the set of all functions with the same parameter and result types."15 "Function literals are closures"15.
- Rust. A named function coerces to a function pointer: "The fn type is called a function pointer."16 Closures "will automatically implement one, two, or all three of these Fn traits"17, and "each closure is also its own distinct type"16. So a function that returns a closure uses "the impl Trait syntax"16, for example
impl Fn(i32) -> i32. - Bash. Functions are not values. "Shell functions are a way to group commands for later execution using a single name for the group."18 A variable can hold the name of a function, and a command that starts with the variable calls that function, because after expansion "the first word is taken to be the name of the command and the remaining words are the arguments"19.
def double(x):
return x * 2
def square(x):
return x * x
def apply_twice(g, x):
return g(g(x))
def adder(n):
def add(x):
return x + n
return add
f = double
print(f(5))
ops = {"double": double, "square": square}
print(ops["square"](4))
print(apply_twice(double, 3))
add5 = adder(5)
print(add5(10))
10
16
12
15
- Verdict: native. A
defmakes a function object. The program stores it in a variable and a dict, passes it toapply_twiceand returns the inner functionaddfromadder.
#include <functional>
#include <iostream>
#include <map>
#include <string>
int twice(int x) { return x * 2; }
int apply_twice(const std::function<int(int)>& g, int x) { return g(g(x)); }
std::function<int(int)> adder(int n) {
return [n](int x) { return x + n; };
}
int main() {
std::function<int(int)> f = twice;
std::cout << f(5) << '\n';
std::map<std::string, std::function<int(int)>> ops = {
{"double", twice},
{"square", [](int x) { return x * x; }},
};
std::cout << ops["square"](4) << '\n';
std::cout << apply_twice(twice, 3) << '\n';
auto add5 = adder(5);
std::cout << add5(10) << '\n';
}
10
16
12
15
- Verdict: native.
std::function<int(int)>holds a plain function or a lambda. The lambda[n](int x) { return x + n; }capturesnby value.
import java.util.Map;
import java.util.function.IntUnaryOperator;
public class Main {
static int twice(int x) {
return x * 2;
}
static int applyTwice(IntUnaryOperator g, int x) {
return g.applyAsInt(g.applyAsInt(x));
}
static IntUnaryOperator adder(int n) {
return x -> x + n;
}
public static void main(String[] args) {
IntUnaryOperator f = Main::twice;
System.out.println(f.applyAsInt(5));
Map<String, IntUnaryOperator> ops = Map.of("double", Main::twice, "square", x -> x * x);
System.out.println(ops.get("square").applyAsInt(4));
System.out.println(applyTwice(Main::twice, 3));
IntUnaryOperator add5 = adder(5);
System.out.println(add5.applyAsInt(10));
}
}
10
16
12
15
- Verdict: native. A method is not a value, but the method reference
Main::twiceand the lambdax -> x * xare. Their type is the functional interfaceIntUnaryOperator, and the call isapplyAsInt.
#include <stdio.h>
static int twice(int x) { return x * 2; }
static int square(int x) { return x * x; }
static int apply_twice(int (*g)(int), int x) { return g(g(x)); }
struct adder {
int n;
};
static int adder_call(const struct adder *a, int x) { return x + a->n; }
int main(void) {
int (*f)(int) = twice;
printf("%d\n", f(5));
int (*ops[])(int) = {twice, square};
printf("%d\n", ops[1](4));
printf("%d\n", apply_twice(twice, 3));
struct adder add5 = {5};
printf("%d\n", adder_call(&add5, 10));
return 0;
}
10
16
12
15
- Verdict: idiom. A pointer to a function can be stored, put in an array and passed. C cannot make a new function at run time, so the adder is a struct with the value
nand a function that takes the struct.
using System;
using System.Collections.Generic;
class Program
{
static int Double(int x)
{
return x * 2;
}
static int ApplyTwice(Func<int, int> g, int x)
{
return g(g(x));
}
static Func<int, int> Adder(int n)
{
return x => x + n;
}
static void Main()
{
Func<int, int> f = Double;
Console.WriteLine(f(5));
var ops = new Dictionary<string, Func<int, int>>
{
["double"] = Double,
["square"] = x => x * x,
};
Console.WriteLine(ops["square"](4));
Console.WriteLine(ApplyTwice(Double, 3));
Func<int, int> add5 = Adder(5);
Console.WriteLine(add5(10));
}
}
10
16
12
15
- Verdict: native. The delegate type
Func<int, int>holds a method group such asDoubleor a lambda. The lambda inAddercapturesn.
function double(x) {
return x * 2;
}
const square = (x) => x * x;
function applyTwice(g, x) {
return g(g(x));
}
function adder(n) {
return (x) => x + n;
}
const f = double;
console.log(f(5));
const ops = { double, square };
console.log(ops.square(4));
console.log(applyTwice(double, 3));
const add5 = adder(5);
console.log(add5(10));
10
16
12
15
- Verdict: native. A function declaration and an arrow function both make function values. An object can hold them as properties.
type IntFn = (x: number) => number;
function double(x: number): number {
return x * 2;
}
const square: IntFn = (x) => x * x;
function applyTwice(g: IntFn, x: number): number {
return g(g(x));
}
function adder(n: number): IntFn {
return (x) => x + n;
}
const f: IntFn = double;
console.log(f(5));
const ops: { [name: string]: IntFn } = { double, square };
console.log(ops["square"](4));
console.log(applyTwice(double, 3));
const add5 = adder(5);
console.log(add5(10));
10
16
12
15
- Verdict: native. The function type expression
(x: number) => numberis the type of the variables, the parametergand the result ofadder.
package main
import "fmt"
func double(x int) int {
return x * 2
}
func applyTwice(g func(int) int, x int) int {
return g(g(x))
}
func adder(n int) func(int) int {
return func(x int) int {
return x + n
}
}
func main() {
f := double
fmt.Println(f(5))
ops := map[string]func(int) int{
"double": double,
"square": func(x int) int { return x * x },
}
fmt.Println(ops["square"](4))
fmt.Println(applyTwice(double, 3))
add5 := adder(5)
fmt.Println(add5(10))
}
10
16
12
15
- Verdict: native.
func(int) intis a function type. A function literal is a closure, so the result ofadderkeepsn.
use std::collections::HashMap;
fn double(x: i32) -> i32 {
x * 2
}
fn apply_twice(g: fn(i32) -> i32, x: i32) -> i32 {
g(g(x))
}
fn adder(n: i32) -> impl Fn(i32) -> i32 {
move |x| x + n
}
fn main() {
let f: fn(i32) -> i32 = double;
println!("{}", f(5));
let mut ops: HashMap<&str, fn(i32) -> i32> = HashMap::new();
ops.insert("double", double);
ops.insert("square", |x| x * x);
println!("{}", ops["square"](4));
println!("{}", apply_twice(double, 3));
let add5 = adder(5);
println!("{}", add5(10));
}
10
16
12
15
- Verdict: native.
fn(i32) -> i32is a function pointer type. A closure that captures nothing coerces to it. The closure fromaddercapturesn, so its type is writtenimpl Fn(i32) -> i32.
double() {
echo $(($1 * 2))
}
square() {
echo $(($1 * $1))
}
add() {
echo $(($1 + $2))
}
apply_twice() {
local g=$1 x=$2
"$g" "$("$g" "$x")"
}
f=double
"$f" 5
declare -A ops=([double]=double [square]=square)
"${ops[square]}" 4
apply_twice double 3
add5=(add 5)
"${add5[@]}" 10
10
16
12
15
- Verdict: idiom. A Bash function is not a value. A variable holds the name of a function, and a command that starts with the variable calls it. The array
add5holds a command name and its first argument, so it works as a function that takes one more argument.
Variations and related ideas
- Second-class functions. In ALGOL, a procedure could be an argument, but no expression could give a procedure as its result. Strachey wrote that "in a sense procedures in ALGOL are second class citizens"20.
- Function pointers and delegates. "Languages where functions are not first-class often still allow one to write higher-order functions through the use of features such as function pointers or delegates."1 A C function pointer has no captured data. A C# delegate and a C++
std::functioncan hold a closure1014. - Higher-order functions. First-class functions make Higher-order function possible: map, filter, sort with a key, and callbacks.
- Closures. A function value that keeps the variables from the place where it was made is a closure. Wikipedia says that lexically scoped first-class functions require "handling references to functions as closures instead of bare function pointers"1.
- Currying. A function that returns a function can take its arguments one at a time. See Currying and partial application.
Pitfalls
Calling the function instead of passing it
f is the function and f(3) is its result. A program that passes f(3) passes a number:
This code runs but gives a wrong answer on purpose.
def double(x):
return x * 2
def apply_twice(g, x):
return g(g(x))
try:
print(apply_twice(double(3), 3))
except TypeError as e:
print(e)
'int' object is not callable
double(3) is 6, so apply_twice gets the number 6 as g. A call needs "a callable object"5, and 6 is not one. Write apply_twice(double, 3), which gives 12.
Two equal functions are not equal
Two functions with the same code are two different values. Wikipedia says: "Two separately defined, but otherwise identical function definitions will be considered unequal."1 In JavaScript, === on objects returns true "only if they refer to the same object"21:
const f = (x) => x * 2;
const g = (x) => x * 2;
console.log(f === g);
console.log(f === f);
false
true
A program that removes a function from a list, or an event handler from an event, must keep the same function value that it added. A second function with the same code does not match. Go does not compare function values at all: "Slice, map, and function types are not comparable."15 A Go function value can only be compared to nil15.
Cost
A function value that is a closure must keep its free variables. SICP says: "The major implementation cost of first-class procedures is that allowing procedures to be returned as values requires reserving storage for a procedure's free variables even while the procedure is not executing."2
History
Christopher Strachey introduced the idea of first-class and second-class objects. "The term was coined by Christopher Strachey in the context of "functions as first-class citizens" in the mid-1960s."1 SICP says that "The notion of first-class status of programming-language elements is due to the British computer scientist Christopher Strachey (1916-1975)."2
Lisp gave procedures first-class status early. SICP says: "Lisp, unlike other common programming languages, awards procedures full first-class status."2 Early Lisp used dynamic scope. "Proper support for lexically scoped first-class functions was introduced in Scheme"1.
References
- First-class function, Wikipedia, the introduction; Concepts; Equality of functions
- Structure and Interpretation of Computer Programs, second edition, Abelson and Sussman, 1.3.4 Procedures as Returned Values, footnotes 64 and 66
- First-class function, MDN Web Docs Glossary, the introduction
- More Control Flow Tools, The Python Tutorial, 4.8 Defining Functions
- Expressions, The Python Language Reference, 6.3.4 Calls
- More on Functions, The TypeScript Handbook, Function Type Expressions
- Lambda Expressions, The Java Tutorials, the introduction
- Package java.util.function, Java SE 25 API, the package description
- Delegates, C# Programming Guide, the introduction
- Lambda expressions and anonymous functions, C# language reference, the introduction
- Pointer declaration, C reference, cppreference.com, Pointers to functions
- Functions, C reference, cppreference.com, Explanation
- Lambda expressions, C++ reference, cppreference.com, the introduction
- std::function, C++ reference, cppreference.com, the introduction
- The Go Programming Language Specification, Function types; Function literals; Comparison operators
- Advanced Functions and Closures, The Rust Programming Language, Function Pointers; Returning Closures
- Closures, The Rust Programming Language, Capturing References or Moving Ownership
- Shell Functions, Bash Reference Manual, 3.3 Shell Functions
- Simple Command Expansion, Bash Reference Manual, 3.7.1 Simple Command Expansion
- First-class citizen, Wikipedia, History
- Strict equality (===), MDN Web Docs, 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 JW0TZE Edit this page History Report an error Markdown