Conceptadvanced
Row polymorphism
Also called row types, row type, row variable, extensible records, open records, open variants.
Row polymorphism lets a function accept any record that has some named fields, and return the record with all its other fields kept. OCaml, PureScript and Elm use it.
- Applies to
- core-languages
Idea
Many functions need only a few fields of a record. A function that moves a point needs x and y. It does not care whether the point also has a z, a label or a color. Row polymorphism gives such a function a type that says exactly this: the input has x and y and any other fields, and the output has the same other fields. Wikipedia describes it as a kind of polymorphism for programs that are "polymorphic on record types and/or variants".1
def shift(p: dict) -> dict:
return {**p, "x": p["x"] + 1}
print(shift({"x": 1, "y": 2}))
print(shift({"x": 1, "y": 2, "label": "home"}))
print(shift({"x": 1, "y": 2, "z": 3, "color": "red"}))
{'x': 2, 'y': 2}
{'x': 2, 'y': 2, 'label': 'home'}
{'x': 2, 'y': 2, 'z': 3, 'color': 'red'}
Python does not check the types of dictionaries, so this code works for any dictionary with an x. A language with row polymorphism checks the same code statically. In PureScript, a function that reads two fields gets the type forall r. { foo :: Int, bar :: Int | r } -> Int. The documentation explains that the function accepts any record that has the properties foo and bar, and any other properties.2 The variable r stands for the other fields.
How it works
Rows. "Formally, a row is an association of labels to types."1 A record type is built from a row, such as { x : Int, y : Int }. A row can be closed, with exactly the listed fields, or open, with a row variable that stands for more fields. PureScript writes an open row with a pipe: ( name :: String, age :: Number | r ).2
Row variables. A function type can mention a row variable, and each call fills it in with the extra fields of the argument. Wikipedia gives the type transform2d : {x:Number, y:Number, ρ} → {x:Number, y:Number, ρ}.1 The same ρ is on both sides, so "There is no loss of information: the type ensures that all the fields represented by the variable ρ are present in the return type."1
Record operations. Selecting a field, adding a field and removing a field all get row-polymorphic types. Some systems also record which fields are absent, so that adding a field cannot make a duplicate label.1
Rows and subtyping. Structural subtyping also lets a function accept a record with extra fields. TypeScript states the rule this way: "x is compatible with y if y has at least the same members as x".3 But with subtyping alone, the return type of the function names only the fields in its signature, and the type checker forgets the other fields. A row variable keeps them in the type. TypeScript code gets the same effect with a generic type parameter constrained by the needed fields, as the TypeScript example shows.
Variants. Rows also describe open variants, that is, open sum types. OCaml polymorphic variants are an example: "a variant tag does not belong to any type in particular, the type system will just check that it is an admissible value according to its use".4 A tag is a name with a backquote, such as `On. An inferred type that starts with [< lists the tags that a function can accept, and a type that starts with [> lists the tags that a value can have. The manual says: "The > and < inside the variant types show that they may still be refined, either by defining more tags or by allowing less."4
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Idiom | |
| Java | Idiom | |
| C | Does not apply | A C function takes one struct type, and C has no generic functions over struct fields. |
| C# | Idiom | |
| JavaScript | Idiom | |
| TypeScript | Idiom | |
| Go | Idiom | |
| Rust | Idiom | |
| Kotlin | Idiom | A generic interface whose methods return the type parameter, as in Java; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | A query names the columns that it uses, and SQL has no functions over rows of any shape. |
| Bash | Does not apply | Bash has no records. |
| PowerShell | Idiom | Objects can have any properties, and nothing checks them before the script runs; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no types. |
| CSS | Does not apply | Style rules have no types. |
| Regular expressions | Does not apply | A pattern has no types. |
The example files define a function that adds 1 to the x field of any record with x and y fields, and return a value of the same type with the other fields kept.
| Language | Verdict | Form |
|---|---|---|
| Python | idiom | a generic function bound by a Protocol, with dataclasses.replace; type checkers check it, the run time does not |
| JavaScript | idiom | object spread; no static types |
| TypeScript | idiom | a type parameter with a constraint, <P extends { x: number; y: number }>; structural types3 |
| Java | idiom | a generic interface whose methods return the type parameter |
| C | n/a | each function takes one struct type |
| C++ | idiom | a template, checked when it is used |
| C# | idiom | a generic method constrained to a base record, and a with expression |
| Go | idiom | a generic function with a constraint interface; type parameters cannot access struct fields |
| Rust | idiom | a generic function bound by a trait |
| Kotlin | idiom | a generic interface, as in Java |
| PowerShell | idiom | objects with extra properties; no static types |
| Bash | n/a | Bash has no records |
| SQL | n/a | a query names its columns |
| Regex | n/a | a pattern has no types |
| HTML/CSS | n/a | markup has no types |
None of these languages has row variables. The examples show the closest idiom in each.
OCaml. "In Ocaml, row polymorphism is used by Ocaml's object types and also by its polymorphic variants. Ordinary record types are not row-polymorphic in Ocaml."1 The manual shows the function let get_succ_x p = p#get_x + 1 with the type < get_x : int; .. > -> int. It applies "to any object p that has this method (and possibly some others, which are represented by an ellipsis in the type)".5
PureScript. Records have row types, and a function that uses some fields accepts any record with those fields.2 The documentation notes that addProps { foo: 1 } does not compile, because the bar property is missing.2 PureScript is listed among the languages that support row polymorphism.1
Elm. An Elm record update keeps the other fields of the record. For the function celebrateBirthday person = { person | age = person.age + 1 }, the Elm guide shows the type { a | age : number } -> { a | age : number }.6 The variable a stands for the other fields.
Standard ML and F#. "Row polymorphism is not supported in Standard ML", but extensions such as SML# support it.1 Wikipedia notes that F# can simulate row polymorphism with "Statically Resolved Type Parameters" in inline functions.1
from dataclasses import dataclass, replace
from typing import Protocol, Self
class HasXY(Protocol):
@property
def x(self) -> int: ...
@property
def y(self) -> int: ...
def with_x(self, x: int) -> Self: ...
@dataclass(frozen=True)
class Point:
x: int
y: int
def with_x(self, x: int) -> Self:
return replace(self, x=x)
@dataclass(frozen=True)
class Labelled:
x: int
y: int
label: str
def with_x(self, x: int) -> Self:
return replace(self, x=x)
def shift[P: HasXY](p: P) -> P:
return p.with_x(p.x + 1)
a = shift(Point(1, 2))
b = shift(Labelled(1, 2, "home"))
print(f"point: x={a.x} y={a.y}")
print(f"labelled: x={b.x} y={b.y} label={b.label}")
print("same class:", "yes" if type(b) is Labelled else "no")
point: x=2 y=2
labelled: x=2 y=2 label=home
same class: yes
- Verdict: idiom. Python has no row types. A
Protocollists the members thatshiftneeds, and the type parameterP(Python 3.12 syntax) makes the result type the same as the argument type. PointandLabelleddo not nameHasXY. A type checker matches them against the protocol by their members.- At run time, Python checks none of this. The idea block shows the same function on plain dictionaries.
#include <iostream>
#include <string>
template <class P>
concept HasXY = requires(P p) {
p.x += 1;
p.y;
};
template <HasXY P>
P shift(P p) {
p.x += 1;
return p;
}
struct Point {
int x;
int y;
};
struct Labelled {
int x;
int y;
std::string label;
};
int main() {
Point a = shift(Point{1, 2});
Labelled b = shift(Labelled{1, 2, "home"});
std::cout << "point: x=" << a.x << " y=" << a.y << '\n';
std::cout << "labelled: x=" << b.x << " y=" << b.y << " label=" << b.label << '\n';
}
point: x=2 y=2
labelled: x=2 y=2 label=home
- Verdict: idiom. A template accepts any type, and the concept
HasXYrequires only the membersxandy. The compiler makes one copy ofshiftfor each type, so the result keeps the full type. PointandLabelleddo not name the concept. The compiler checks the members when it uses the template, which is close to a row type checked at compile time.
interface HasXY<P extends HasXY<P>> {
int x();
int y();
P withX(int x);
}
record Point(int x, int y) implements HasXY<Point> {
public Point withX(int x) {
return new Point(x, y);
}
}
record Labelled(int x, int y, String label) implements HasXY<Labelled> {
public Labelled withX(int x) {
return new Labelled(x, y, label);
}
}
public class Main {
static <P extends HasXY<P>> P shift(P p) {
return p.withX(p.x() + 1);
}
public static void main(String[] args) {
Point a = shift(new Point(1, 2));
Labelled b = shift(new Labelled(1, 2, "home"));
System.out.println("point: x=" + a.x() + " y=" + a.y());
System.out.println("labelled: x=" + b.x() + " y=" + b.y() + " label=" + b.label());
}
}
point: x=2 y=2
labelled: x=2 y=2 label=home
- Verdict: idiom. Java types are nominal, so each record must name the interface
HasXY. The type parameterPletsshiftreturn the same record type that it gets, sobis aLabelled. - Each record writes its own
withX, because only the record knows how to copy its other fields.
using System;
static P Shift<P>(P p) where P : Point
{
Point q = p;
Point moved = q with { X = q.X + 1 };
return (P)moved;
}
Point a = Shift(new Point(1, 2));
Labelled b = Shift(new Labelled(1, 2, "home"));
Console.WriteLine($"point: x={a.X} y={a.Y}");
Console.WriteLine($"labelled: x={b.X} y={b.Y} label={b.Label}");
Console.WriteLine($"run time type: {b.GetType().Name}");
record Point(int X, int Y);
record Labelled(int X, int Y, string Label) : Point(X, Y);
point: x=2 y=2
labelled: x=2 y=2 label=home
run time type: Labelled
- Verdict: idiom.
Labelledderives fromPoint, andShiftaccepts any type derived fromPoint. The type parameterPkeeps the full type in the result. - A
withexpression copies the record with its run time type, so the copy of aLabelledis still aLabelledwith itsLabel. The cast back toPis safe for that reason. - Every type that
Shiftaccepts must derive fromPoint. A row type would accept any record with the fields.
const shift = (p) => ({ ...p, x: p.x + 1 });
const a = shift({ x: 1, y: 2 });
const b = shift({ x: 1, y: 2, label: "home" });
console.log(`point: x=${a.x} y=${a.y}`);
console.log(`labelled: x=${b.x} y=${b.y} label=${b.label}`);
console.log("keys:", Object.keys(b).join(" "));
point: x=2 y=2
labelled: x=2 y=2 label=home
keys: x y label
- Verdict: idiom. JavaScript has no static types, so any object with an
xworks. The spread...pcopies all the other properties into the new object. - Nothing checks that the argument has
xandybefore the program runs. A missingxgivesNaN, not an error.
type XY = { x: number; y: number };
function shift<P extends XY>(p: P): P {
return { ...p, x: p.x + 1 };
}
function shiftFixed(p: XY): XY {
return { ...p, x: p.x + 1 };
}
const home = { x: 1, y: 2, label: "home" };
const a = shift({ x: 1, y: 2 });
const b = shift(home);
console.log(`point: x=${a.x} y=${a.y}`);
console.log(`labelled: x=${b.x} y=${b.y} label=${b.label}`);
const c = shiftFixed(home);
// c.label does not compile: the type of c is XY.
console.log("label still in the object:", "label" in c ? "yes" : "no");
point: x=2 y=2
labelled: x=2 y=2 label=home
label still in the object: yes
- Verdict: idiom. The type parameter
Pwith the constraintextends XYplays the part of a row variable:shiftaccepts any object withxandy, and its result has the full type of the argument, sob.labelcompiles. shiftFixeduses only structural subtyping. It acceptshome, but its result type isXY, so the type checker forgetslabel, although the object still has it.
package main
import "fmt"
type HasXY[P any] interface {
XY() (int, int)
WithX(x int) P
}
type Point struct{ X, Y int }
func (p Point) XY() (int, int) { return p.X, p.Y }
func (p Point) WithX(x int) Point {
p.X = x
return p
}
type Labelled struct {
Point
Label string
}
func (l Labelled) WithX(x int) Labelled {
l.X = x
return l
}
func Shift[P HasXY[P]](p P) P {
x, _ := p.XY()
return p.WithX(x + 1)
}
func main() {
a := Shift(Point{1, 2})
b := Shift(Labelled{Point{1, 2}, "home"})
fmt.Printf("point: x=%d y=%d\n", a.X, a.Y)
fmt.Printf("labelled: x=%d y=%d label=%s\n", b.X, b.Y, b.Label)
}
point: x=2 y=2
labelled: x=2 y=2 label=home
- Verdict: idiom. A generic function cannot read a struct field through a type parameter, so the constraint
HasXY[P]lists methods instead. Its type parameter makesWithXreturn the same type. LabelledembedsPoint, so it gets theXYmethod and the fieldsXandY. It must still write its ownWithX, because the method ofPointreturns aPoint.
trait HasXY: Sized {
fn x(&self) -> i32;
fn y(&self) -> i32;
fn with_x(self, x: i32) -> Self;
}
struct Point {
x: i32,
y: i32,
}
struct Labelled {
x: i32,
y: i32,
label: String,
}
impl HasXY for Point {
fn x(&self) -> i32 {
self.x
}
fn y(&self) -> i32 {
self.y
}
fn with_x(self, x: i32) -> Self {
Point { x, ..self }
}
}
impl HasXY for Labelled {
fn x(&self) -> i32 {
self.x
}
fn y(&self) -> i32 {
self.y
}
fn with_x(self, x: i32) -> Self {
Labelled { x, ..self }
}
}
fn shift<P: HasXY>(p: P) -> P {
let x = p.x();
p.with_x(x + 1)
}
fn main() {
let a = shift(Point { x: 1, y: 2 });
let b = shift(Labelled { x: 1, y: 2, label: String::from("home") });
println!("point: x={} y={}", a.x, a.y);
println!("labelled: x={} y={} label={}", b.x, b.y, b.label);
}
point: x=2 y=2
labelled: x=2 y=2 label=home
- Verdict: idiom. Traits cannot require fields, only methods, so
HasXYhas accessor methods. The boundP: HasXYkeeps the full type of the argument in the result. - The struct update syntax
Labelled { x, ..self }copies the other fields, sowith_xdoes not list them.
Variations and related ideas
- Structural subtyping. A record with more fields is a subtype of a record with fewer. It accepts the same arguments, but it forgets the extra fields in the result. See Subtyping.
- Extensible records. Records that can gain or lose fields with typed operations.1
- Open variants. Sum types to which other code can add cases, such as OCaml polymorphic variants.4 See Sum types.
- Effect rows. "In the modern day, row types are most commonly used to type extensible algebraic effects."1 Wikipedia names Links and Koka as languages that use rows for effect types.1
- Duck typing. Dynamic languages accept any object with the needed fields, but check nothing before the program runs. See duck-typing.
Pitfalls
Subtyping forgets the extra fields
A function that takes and returns a fixed record type accepts a larger record but returns the smaller type. In TypeScript the extra fields are still in the object at run time, but the type checker does not let the program use them. A generic type parameter keeps the full type. The TypeScript example shows both forms.
A literal with extra fields is an error in TypeScript
TypeScript applies excess property checking to object literals: "Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments."7 A literal with a property that the target type does not have is an error. So a call such as shift({ x: 1, y: 2, label: "home" }) to a function that takes { x: number; y: number } fails, but the same object passed through a variable is accepted, because a variable does not get excess property checks.7 A generic function with a constraint accepts both forms.
Duplicate labels
A row system must say what happens when a record gains a field that it already has. Wikipedia notes that the theory "is somewhat complicated by the need to have distinct labels in a record".1 Some systems forbid the duplicate, and PureScript keeps both: duplicate labels "have their types collected together in order".2
Cost
Row polymorphism is a property of the type system. In a language that compiles a record to a fixed layout, a row-polymorphic function cannot know the offset of a field at compile time, so an implementation passes the offset, looks up the field by name, or compiles a separate copy of the function for each record type. Dynamic languages look up fields by name. So does PureScript: "PureScript records correspond to JavaScript objects."2
History
"Row types and row polymorphism were introduced by Mitchell Wand in the late 1980s as an approach to structurally typing extensible records and variants."1 Wikipedia cites Wand's 1987 paper on complete type inference for simple objects. Rémy found that the original inference algorithm was not complete, and both Rémy and Wand corrected it.1 The first version of SML# added row polymorphism to Standard ML, based on a 1989 paper by Ohori and colleagues.1 OCaml uses rows for its object types and polymorphic variants.154
References
- Row polymorphism, Wikipedia, the introduction; History; Theory; Row-polymorphic record type definition; Implementations
- PureScript documentation, Types, Row Polymorphism; Rows
- TypeScript Handbook, Type Compatibility, Starting out
- The OCaml Manual, Chapter 5 Polymorphic variants, the introduction; 5.1 Basic use
- The OCaml Manual, Chapter 3 Objects in OCaml, 3.4 Immediate objects and object types (get_succ_x)
- An Introduction to Elm, Core Language, Records
- TypeScript Handbook, Object Types, Excess Property Checks
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 66NR5A Edit this page History Report an error Markdown