Conceptcore
Type constructor
Also called type operator, generic type, parameterized type, generic type definition, unbound generic type, kind, higher-kinded type.
A type constructor builds a type from other types: List makes List of Int from Int. Its arity is the number of types it takes, and its kind describes what it takes and gives.
- Applies to
- core-languages
Idea
int and str are types: a value can have the type int. list is different. A list holds items of some type, and list[int] and list[str] are two types made from one name. list takes a type and gives a type, so it works like a function from types to types. That function is a type constructor. dict takes two types, a key type and a value type. Python shows them at run time.
from typing import get_args, get_origin
# Built-in type constructors: list takes one type, dict takes two.
print(list[int], dict[str, list[int]])
print(get_origin(dict[str, int]), get_args(dict[str, int]))
# A generic class is a type constructor that the program defines.
class Box[T]:
def __init__(self, item: T) -> None:
self.item = item
# A generic type alias is one too.
type Pair[A, B] = tuple[A, B]
print(Box[str], Pair[int, str], Pair.__type_params__)
# Python does not check the argument when the program runs.
b = Box[int]("not an int")
print(type(b).__name__, b.item)
list[int] dict[str, list[int]]
<class 'dict'> (<class 'str'>, <class 'int'>)
__main__.Box[str] Pair[int, str] (A, B)
Box not an int
list[int] is a type made by applying list to int, and dict[str, list[int]] applies dict to two types, one of which is itself made by list. get_origin returns the constructor and get_args returns the types it was applied to. Box and Pair are type constructors that the program defines. The last line shows that the type arguments are for a static checker: Python makes a plain Box and does not look at int.
How it works
Types from types. A type constructor "is a feature of a typed formal language that builds new types from old ones"1. "Abstractly, a type constructor is an n-ary type operator taking as argument zero or more types, and returning another type"1. In Python, list[int] "is a GenericAlias object created by subscripting the list class with the argument int"2. In Haskell, "Maybe and IO are unary type constructors"3.
Arity. The arity of a type constructor is the number of types it takes. "Basic types are considered to be built using nullary type constructors"1, so Int has arity 0. A list or an option type takes one type. A map takes two: the .NET type Dictionary<TKey,TValue> "has two type parameters, TKey and TValue"4. A function type takes the parameter types and the result type. "Some type constructors take another type as an argument, e.g., the constructors for product types, function types, power types and list types"1.
Declared constructors. In most languages with generics, a generic class, interface or struct is a type constructor. "A generic type is a generic class or interface that is parameterized over types"5. Applying it gives a type: "An invocation of a generic type is generally known as a parameterized type"5, such as Box<Integer>. In Go, a generic type "is instantiated by substituting type arguments for the type parameters"6. A recursive type can use the constructor in its own definition, as a tree uses a list of trees.
Built-in constructors. Some type constructors have special syntax. In Haskell, "The list type is written as [] and has kind ∗→∗"3, and the function type (->) takes two types. C has no generics, but its array, pointer and function types are derived types7: int[10], int * and int (int) are built from int.
Kinds. Types classify values, and kinds classify types. A kind "is the type of a type constructor"8. In Haskell, "The symbol ∗ represents the kind of all nullary type constructors"3, and "κ1 → κ2 is the kind of types that take a type of kind κ1 and return a type of kind κ2"3. So Int has kind ∗, a list has kind ∗→∗, and a pair has kind ∗→∗→∗. A kind checks that a type expression is valid: a list applied to Int is a type, but a list applied to nothing, or applied to a list constructor, is not.
A constructor is not a type. A value has a type of kind ∗ only. The C# specification says: "An unbound generic type is not itself a type, and cannot be used as the type of a variable, argument or return value, or as a base type"9. A variable can be a List<int>, but not a List<>.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Does not apply | JavaScript has no static types, so it has no type constructors. An array or a Map can hold values of any type. |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has generic classes and interfaces, such as List<T> and Map<K, V>, and the program can declare its own. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | The column types of a table are fixed by the database, and a query does not define type constructors. |
| Bash | Does not apply | Bash has no types for its values, so it has no type constructors. |
| PowerShell | Native | PowerShell can use the generic types of .NET with type arguments, such as a List of int. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types of values. |
| CSS | Does not apply | CSS has no types in this sense. |
| Regular expressions | Does not apply | A regular expression has no values and no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | list[int], dict[str, int]; generic classes class Box[T]; generic type aliases type Pair[A, B] |
| JavaScript | n/a | no types in the language, so no type constructors |
| TypeScript | native | Array<T>, Map<K, V>; generic interfaces, classes and type aliases |
| Java | native | generic classes and interfaces; List<String>; raw types for old code |
| Kotlin | native | generic classes and interfaces; List<String>, Map<K, V> |
| C# | native | generic classes, structs and interfaces; List<int>; typeof(List<>) for the unbound type |
| Go | native | built-in slice, map, pointer and channel types; generic types with type parameters |
| Rust | native | generic structs and enums: Vec<T>, Option<T>, HashMap<K, V> |
| C | idiom | built-in array, pointer and function types only; macros make a struct for each element type |
| C++ | native | class templates such as std::vector<T>; template template parameters |
| Bash | n/a | no types |
| PowerShell | native | .NET generic types, written as [System.Collections.Generic.List[int]] |
| SQL | n/a | column types are fixed by the database, and a query defines no type constructors |
| Regex | n/a | a pattern has no types |
| HTML | n/a | HTML has no types |
| CSS | n/a | CSS has no types in this sense |
Most languages with generics let the program declare its own type constructors as generic classes or types. Go and C have built-in constructors with special syntax, such as []int and int *. C++ goes further than the others: a template can take a class template as a parameter. Python and TypeScript check the type arguments only before the program runs.
The example files show these differences. Python shows get_origin and get_args. TypeScript shows a generic type alias and a generic interface. Java shows a generic class and a raw type. C# shows an unbound generic type and its arity. Go shows a generic type and the built-in map type. Rust shows Option and Vec with the type Vec<Option<i32>>. C shows a macro that makes a struct for each element type. C++ shows a template template parameter.
from collections.abc import Callable
from typing import get_args, get_origin
# Each type is a constructor applied to arguments.
for t in (list[int], dict[str, list[int]], tuple[int, str], Callable[[int], str]):
print(t, "=", get_origin(t), get_args(t))
# int is a nullary constructor: it takes no arguments.
print(int, get_origin(int), get_args(int))
list[int] = <class 'list'> (<class 'int'>,)
dict[str, list[int]] = <class 'dict'> (<class 'str'>, list[int])
tuple[int, str] = <class 'tuple'> (<class 'int'>, <class 'str'>)
collections.abc.Callable[[int], str] = <class 'collections.abc.Callable'> ([<class 'int'>], <class 'str'>)
<class 'int'> None ()
- Verdict: native.
get_originreturns the type constructor andget_argsreturns the type arguments.listtakes one type,dicttakes two, andtupletakes any number.Callabletakes the list of parameter types and the result type.intis not built from other types, so it has no origin and no arguments.
#include <iostream>
#include <list>
#include <string>
#include <vector>
// Table takes two types and a type constructor C, such as std::vector.
template <typename K, typename V, template <typename...> typename C>
struct Table {
C<K> keys;
C<V> values;
void add(const K& k, const V& v) {
keys.push_back(k);
values.push_back(v);
}
};
int main() {
Table<std::string, int, std::vector> a;
Table<std::string, int, std::list> b;
a.add("x", 1);
b.add("y", 2);
std::cout << a.keys[0] << ' ' << a.values.size() << ' ' << b.values.front() << '\n';
// std::vector<int> is a type; std::vector alone is a class template.
std::vector<std::vector<int>> grid{{1, 2}, {3}};
std::cout << grid.size() << ' ' << grid[0].size() << '\n';
}
x 1 2
2 2
- Verdict: native. A class template such as
std::vectoris a type constructor, andstd::vector<int>is a type.Tablehas a template template parameterC, so it takes a type constructor as an argument. This is a higher-kinded parameter: the sameTableworks withstd::vectorand withstd::list.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Main {
// A generic class: Box is a type constructor, Box<String> is a type.
static final class Box<T> {
private final T item;
Box(T item) {
this.item = item;
}
T get() {
return item;
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
public static void main(String[] args) {
Box<String> b = new Box<>("hi");
Map<String, List<Integer>> m = Map.of("a", List.of(1, 2));
System.out.println(b.get().length() + " " + m.get("a"));
// A raw type: the compiler no longer checks the items.
List raw = new ArrayList<String>();
raw.add(42);
List<String> strings = raw;
try {
String s = strings.get(0);
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("ClassCastException");
}
// The type argument is erased: both lists have one class.
System.out.println(new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass());
}
}
2 [1, 2]
ClassCastException
true
- Verdict: native.
Box<T>is a generic class, andBox<String>is a parameterized type.List rawis a raw type: the compiler lets the program add anIntegerto a list of strings, and the error comes later, when the program reads the item as aString. The@SuppressWarningshides the warnings that the compiler gives for this code. The last line printstrue, because Java erases the type arguments.
#include <stdio.h>
// C has no generic types. A macro writes one struct for each element type.
#define DEFINE_PAIR(name, A, B) \
typedef struct { \
A first; \
B second; \
} name
DEFINE_PAIR(pair_int_str, int, const char *);
DEFINE_PAIR(pair_dbl_dbl, double, double);
int main(void) {
pair_int_str p = {42, "age"};
pair_dbl_dbl q = {1.5, 2.5};
// The built-in constructors: array, pointer and function types.
int a[3] = {1, 2, 3};
int *ptr = a;
int (*fn)(const char *, ...) = printf;
fn("%d %s %.1f %d %zu\n", p.first, p.second, q.first + q.second, ptr[2], sizeof a / sizeof a[0]);
return 0;
}
42 age 4.0 3 3
- Verdict: idiom. The macro
DEFINE_PAIRtakes two types and makes a struct type, but each use writes a different struct with its own name. C has no name for "a pair of A and B", so the compiler cannot relatepair_int_strandpair_dbl_dbl. The built-in derived types are type constructors:int[3],int *and a pointer to a function are built from other types.
using System;
using System.Collections.Generic;
// typeof(List<>) is the unbound generic type; List<int> is a closed type.
Type unbound = typeof(List<>);
Type closed = typeof(List<int>);
Type map = typeof(Dictionary<,>);
Console.WriteLine($"{unbound.Name} {unbound.IsGenericTypeDefinition} {unbound.GetGenericArguments().Length}");
Console.WriteLine($"{map.Name} {map.GetGenericArguments().Length}");
Console.WriteLine($"{closed.Name} {closed.GetGenericArguments()[0].Name}");
// Apply the constructor to a type when the program runs.
Type made = unbound.MakeGenericType(typeof(string));
Console.WriteLine($"{made == typeof(List<string>)} {made == closed}");
List`1 True 1
Dictionary`2 2
List`1 Int32
True False
- Verdict: native.
typeof(List<>)names the unbound generic type, which is not a type for a variable. Its .NET name ends in the arity:List`1takes one type andDictionary`2takes two.MakeGenericTypeapplies the constructor tostringwhen the program runs. .NET keeps the type arguments, soList<string>andList<int>are different types at run time.
// A generic type alias: Pair takes two types and gives a tuple type.
type Pair<A, B> = [A, B];
// A generic interface: Tree takes one type and refers to itself.
interface Tree<T> {
value: T;
children: Tree<T>[];
}
const p: Pair<string, number> = ["age", 42];
const t: Tree<string> = {
value: "root",
children: [{ value: "leaf", children: [] }],
};
// Built-in constructors: Array<T> is the same type as T[], and Map takes two types.
const counts: Map<string, Array<number>> = new Map([["a", [1, 2]]]);
console.log(p, t.children[0].value, counts.get("a"));
[ 'age', 42 ] leaf [ 1, 2 ]
- Verdict: native.
PairandTreeare type constructors that the program declares.Pair<string, number>andTree<string>are the types made from them.ArrayandMapare built in. The types are erased when the program runs, so the output shows only the values.
package main
import "fmt"
// Stack is a generic type: Stack[int] and Stack[string] are types.
type Stack[T any] struct {
items []T
}
func (s *Stack[T]) Push(x T) { s.items = append(s.items, x) }
func (s *Stack[T]) Pop() T {
x := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return x
}
func main() {
var s Stack[string]
s.Push("a")
s.Push("b")
fmt.Println(s.Pop(), len(s.items))
// Built-in constructors: slice, map and pointer types.
m := map[string][]int{"a": {1, 2}}
p := &m
fmt.Printf("%T %T %v\n", m, p, (*p)["a"])
fmt.Printf("%T\n", s)
}
b 1
map[string][]int *map[string][]int [1 2]
main.Stack[string]
- Verdict: native.
Stackhas a type parameter, soStack[string]is a type made from it. A generic type in Go must have its type arguments;Stackalone is not a type. The slice, map and pointer types are built-in constructors with special syntax:map[string][]intapplies the map constructor tostringand to[]int.
use std::collections::HashMap;
fn main() {
// Option and Vec take one type; HashMap takes two.
let xs: Vec<Option<i32>> = vec![Some(1), None, Some(3)];
let total: i32 = xs.iter().flatten().sum();
let mut m: HashMap<&str, Vec<i32>> = HashMap::new();
m.entry("a").or_default().push(total);
println!("{xs:?} {total} {m:?}");
println!("{}", std::any::type_name::<Vec<Option<i32>>>());
}
[Some(1), None, Some(3)] 4 {"a": [4]}
alloc::vec::Vec<core::option::Option<i32>>
- Verdict: native.
OptionandVecare generic types with one type parameter, andHashMaphas two.Vec<Option<i32>>appliesVecto a type that is itself made byOption.
A type constructor without its type argument is not a type:
This code does not compile, on purpose.
fn total(xs: &Vec) -> usize {
xs.len()
}
fn main() {
println!("{}", total(&vec![1, 2]));
}
The compiler reports error E0107: the struct Vec needs a type argument. Write &Vec<i32>, or make total generic.
Variations and related ideas
- Higher-kinded types. A type constructor can take another type constructor. "(∗→∗)→∗ is the kind of a higher-order type operator from unary type constructors to proper types"8. Haskell allows this, and C++ has template template parameters, such as
template<typename> typename Cin the declaration of a class that usesC<K>andC<V>10. Most languages with generics do not: "Since higher-order type operators are uncommon in programming languages, in most programming practice, kinds are used to distinguish between data types and the types of constructors which are used to implement parametric polymorphism"8. - Partial application. In Haskell, a type constructor "takes one or more type arguments, and produces a data type when enough arguments are supplied, i.e. it supports partial application thanks to currying"8. A pair constructor applied to one type gives a constructor of kind ∗→∗.
- Data constructors. A type constructor builds a type. A data constructor, such as
JustorSome, builds a value of that type. In Haskell, both start with a capital letter: "As with data constructors, the names of type constructors start with uppercase letters"3. See algebraic data types. - Type erasure. Java removes the type arguments when it compiles, and Python does not keep them in the objects: "parameterized generics erase type parameters during object creation"2. C# keeps them: "At run-time, all of the code within a generic type declaration is executed in the context of a closed constructed type that was created by applying type arguments to the generic declaration"9. See type erasure.
Pitfalls
- A raw type in Java. "A raw type is the name of a generic class or interface without any type arguments"11. Java accepts it for old code, but the compiler cannot check the items: "When using raw types, you essentially get pre-generics behavior"11. Write
List<String>, notList. The Java example shows a raw type. - Type arguments that nobody checks. Python does not check the type arguments when the program runs. The documentation shows that
list[str]([1, 2, 3])gives[1, 2, 3]2, and "The Python runtime does not enforce type annotations"2. TypeScript erases the types too. Run a type checker to find these errors. - A missing type argument. Most languages with generics reject a constructor in the place of a type. In Rust, a parameter of type
Vecwith no type argument is a compile error. The Rust example shows the error. - Two types that look the same.
List<int>andList<long>are different types, even whenintconverts tolong. A function that takes one does not take the other. The rules for this are variance.
Cost
A type constructor costs nothing when the program runs in a language that erases the type arguments, such as Python, TypeScript and Java. Rust makes separate code for each type argument instead: "Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled"12. So the program does not get slower, but each Vec<T> with a different T adds machine code. In .NET, the code of a generic type runs "in the context of a closed constructed type"9.
History
The Haskell report defines kinds and type application for Haskell type expressions: "If t1 is a type of kind κ1 → κ2 and t2 is a type of kind κ1, then t1 t2 is a type expression of kind κ2"3. In Haskell, "all data type declarations are considered to declare type constructors"1. Benjamin Pierce treats type operators and kinding in chapter 29 of Types and Programming Languages (2002)1.
References
- Type constructor, Wikipedia, Whole article
- Built-in Types, Python 3.14 documentation, Generic Alias Type
- Haskell 2010 Language Report, Chapter 4, Declarations and Bindings, 4.1.1 Kinds; 4.1.2 Syntax of Types
- Generics in .NET, .NET documentation, Defining and using generics; Generics terminology
- Generic Types, The Java Tutorials, Whole page
- The Go Programming Language Specification, Instantiations
- Type, C reference, cppreference.com, Type classification
- Kind (type theory), Wikipedia, Introduction; Examples; Kinds in Haskell
- Types, C# language specification, 8.4 Constructed types; 8.4.4 Bound and unbound types; 8.4.5 Open and closed types
- Template parameters and template arguments, C++ reference, cppreference.com, Template template parameter
- Raw Types, The Java Tutorials, Whole page
- Generic Data Types, The Rust Programming Language, Performance of Code Using Generics
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 SSJ9MR Edit this page History Report an error Markdown