Programming Search⌘K

Conceptcore

Product type

Also called product type, product, cartesian product type, pair type, struct type, composite type, unit type.

A value of a product type holds one value of each of its parts at the same time. Records, structs and tuples are product types, and the unit type is the product with no parts.

Applies to
core-languages

Idea

A product type holds several values at the same time. A point has an x coordinate and a y coordinate. A playing card has a rank and a suit. Each value of the type has exactly one value for each part.

The name comes from sets. "The set of all possible values of a product type is the Cartesian product of the sets of its component types."1 So the number of values of a product is the product of the numbers of values of its parts. Three ranks and two suits give six cards.

from dataclasses import dataclass
from itertools import product


@dataclass(frozen=True)
class Card:
    rank: str
    suit: str


ranks = ["A", "K", "Q"]
suits = ["clubs", "hearts"]
cards = [Card(r, s) for r, s in product(ranks, suits)]

print(len(cards), "cards from", len(ranks), "ranks and", len(suits), "suits")
print(cards[0])
print("equal to Card('A', 'clubs'):", "yes" if cards[0] == Card("A", "clubs") else "no")
Output
6 cards from 3 ranks and 2 suits
Card(rank='A', suit='clubs')
equal to Card('A', 'clubs'): yes

Products come in two forms. A tuple names its parts by position: the first part, the second part. A record or a struct names its parts by field name. In many languages, "product types take the form of a record type, for which the components of a tuple can be accessed by label".2

How it works

Build and take apart. A product has one way to build a value: give a value for each part. It has one way to read a part: a projection, which selects one component by position or by name. A tuple t in Rust has the parts t.0 and t.1. A struct p has the parts p.x and p.y. Rust names the difference: "Unlike with tuples, in a struct you'll name each piece of data so it's clear what the values mean."3 Many languages can also take apart a product in one step, as in let (x, y) = t; or x, y = t.

Counting. A product of a type with a values and a type with b values has a × b values. A pair (a, b) "has an inhabitant for each combination of a s and b s".4 So a product of two booleans has 4 values, and a struct of two 32-bit integers has 2^64 values.

The unit type. A product with no parts has exactly one value. This is the unit type, "the product of no types".5 In Rust, "The tuple without any values has a special name, unit", and its value and its type are both written ().6 A function that returns nothing useful returns the unit. The unit acts as the number 1 for products: a product of A and the unit has as many values as A.

Order. The parts of a product have a fixed order: "the structure of a product type is determined by the fixed order of the operands in the product".2 So (int, string) and (string, int) are different types, even though they hold the same information. A record also has an order of fields. It shows in positional constructors, in printing and in memory.

Equality. Two values of a product are equal when each pair of corresponding parts is equal. The languages state this rule in their own words:

  • Go: "Two struct values are equal if their corresponding non-blank field values are equal."7
  • Java: the equals method of a record returns true "if and only if the argument is an instance of R, and the current instance is equal to the argument instance at every record component of R".8
  • Python: "Sequences compare lexicographically using comparison of corresponding elements."9
  • C#: "Tuple types support equality operators == and != ."10 The record modifier makes the compiler "generate value equality".11

Some languages do not compare products by value. In JavaScript, === on two objects returns true "only if they refer to the same object".12 In C, == does not accept two structures at all. Its operands must be arithmetic values or pointers.13 The Pitfalls show both cases.

Memory. A product stores its parts next to each other. In C, the members of a structure "have addresses that increase in the order in which they are declared", and "There may be unnamed padding within a structure object, but not at its beginning".13 So the size of a struct is at least the sum of the sizes of its members.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaNative
CNative
C#Native
JavaScriptIdiom
TypeScriptNative
GoNative
RustNative
KotlinNativeA data class is a product by name, and the standard library has Pair and Triple for products by position; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLNativeA row of a table is a product of its columns, and a row value such as (1, 'a') is a product by position.
BashDoes not applyBash has no types, only strings and arrays of strings. Alternative: One variable for each part, or an associative array with one key for each field.
PowerShellIdiomA pscustomobject or a class holds named properties, and an array holds values by position; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no types.
CSSDoes not applyStyle rules have no types.
Regular expressionsDoes not applyA pattern has no types.

The example files build a product by position and by name, read its parts, compare two values and show the unit, where the language has one.

Language Verdict By position By name Unit
Python native tuple a dataclass14 or NamedTuple ()
JavaScript idiom an array an object none
TypeScript native a tuple type [number, string] an object type [] as a type
Java native none a record a record with no components
C native none a struct none in ISO C13
C++ stdlib std::pair, std::tuple15 a struct std::tuple<>
C# native a tuple (int, int)10 a record or a struct a record with no members
Go native none a struct struct{}, size 07
Rust native a tuple (i32, i32)6 a struct3 ()6
Kotlin native Pair, Triple16 a data class16 Unit
PowerShell idiom an array a [pscustomobject] or a class none
Bash n/a no types no types no types
SQL native a row value (1, 'a') a row of a table none
Regex n/a a pattern has no types
HTML/CSS n/a markup has no types

C. A structure "describes a sequentially allocated nonempty set of member objects".13 A structure with no named members has undefined behavior in ISO C, so C has no unit type.13 Some compilers accept an empty struct as an extension.

C++. A struct with no data members is allowed, but a complete object of it has a nonzero size, and unless it is a bit-field, "an object with nonzero size shall occupy one or more bytes of storage".17 std::tuple gives "heterogeneous, fixed-size collections of values".15

Go. Go has no tuple type. A function can return several results, but the results are not one value. The empty struct struct{} is the unit. "A struct or array type has size zero if it contains no fields (or elements, respectively) that have a size greater than zero."7

Python. A tuple is a product by position. The dataclasses module adds generated methods such as __init__() and __repr__() to a class with typed fields, and so makes a product by name.14 A frozen dataclass also compares its fields for equality.

PythonGitHub
from dataclasses import dataclass


@dataclass(frozen=True)
class Point:
    x: int
    y: int


def yn(b: bool) -> str:
    return "yes" if b else "no"


t = (3, 4)  # parts by position
x, y = t
print("tuple:", t, "x =", x, "y =", y)

p = Point(3, 4)  # parts by name
print("record:", p, "x =", p.x, "y =", p.y)
print("same parts equal:", yn(p == Point(3, 4)))
print("swapped parts equal:", yn(p == Point(4, 3)))
print("unit:", (), "equal to unit:", yn(() == ()))
Output
tuple: (3, 4) x = 3 y = 4
record: Point(x=3, y=4) x = 3 y = 4
same parts equal: yes
swapped parts equal: no
unit: () equal to unit: yes
  • Verdict: native. A tuple is a product by position, and a dataclass is a product by name.
  • The dataclass generates __init__, __repr__ and __eq__, so two points with the same fields are equal.
  • The empty tuple () has one value, so it acts as the unit.
#include <iostream>
#include <string>
#include <tuple>
#include <utility>

struct Point {
    int x;
    int y;
    bool operator==(const Point&) const = default;
};

struct Empty {};

const char* yn(bool b) { return b ? "yes" : "no"; }

int main() {
    std::pair<int, int> t{3, 4};  // parts by position
    auto [x, y] = t;
    std::cout << "pair: x = " << x << " y = " << y << " first = " << t.first << "\n";

    std::tuple<int, std::string, bool> r{3, "four", true};
    std::cout << "tuple: " << std::get<0>(r) << " " << std::get<1>(r) << " " << yn(std::get<2>(r)) << "\n";

    Point p{3, 4};  // parts by name
    std::cout << "struct: x = " << p.x << " y = " << p.y << "\n";
    std::cout << "same parts equal: " << yn(p == Point{3, 4}) << "\n";
    std::cout << "swapped parts equal: " << yn(p == Point{4, 3}) << "\n";
    std::cout << "empty tuples equal: " << yn(std::tuple<>{} == std::tuple<>{}) << "\n";
    std::cout << "size of an empty struct: " << sizeof(Empty) << "\n";
}
Output
pair: x = 3 y = 4 first = 3
tuple: 3 four yes
struct: x = 3 y = 4
same parts equal: yes
swapped parts equal: no
empty tuples equal: yes
size of an empty struct: 1
  • Verdict: stdlib. std::pair and std::tuple are products by position, and a struct is a product by name.
  • A defaulted operator== compares the members in order.
  • An empty struct is allowed, but an object of it uses at least one byte.
JavaGitHub
public class Main {
    record Point(int x, int y) {}

    record Unit() {}

    static String yn(boolean b) {
        return b ? "yes" : "no";
    }

    public static void main(String[] args) {
        Point p = new Point(3, 4);
        System.out.println("record: " + p + " x = " + p.x() + " y = " + p.y());
        System.out.println("same parts equal: " + yn(p.equals(new Point(3, 4))));
        System.out.println("swapped parts equal: " + yn(p.equals(new Point(4, 3))));
        System.out.println("same object (==): " + yn(p == new Point(3, 4)));
        System.out.println("unit: " + new Unit() + " equal to unit: " + yn(new Unit().equals(new Unit())));
    }
}
Output
record: Point[x=3, y=4] x = 3 y = 4
same parts equal: yes
swapped parts equal: no
same object (==): no
unit: Unit[] equal to unit: yes
  • Verdict: native. A record is a product by name. Java has no tuple type.
  • equals compares the components, but == compares references.
  • A record with no components has one value up to equals, so it can act as a unit.
#include <stdbool.h>
#include <stdio.h>

struct point {
    int x;
    int y;
};

static const char *yn(bool b) { return b ? "yes" : "no"; }

/* C has no == for structures, so compare the members. */
static bool point_equal(struct point a, struct point b) {
    return a.x == b.x && a.y == b.y;
}

int main(void) {
    struct point p = { 3, 4 };           /* members by position */
    struct point q = { .y = 4, .x = 3 }; /* members by name */
    printf("struct: x = %d y = %d\n", p.x, p.y);
    printf("named initializer: x = %d y = %d\n", q.x, q.y);
    printf("same parts equal: %s\n", yn(point_equal(p, q)));
    printf("swapped parts equal: %s\n", yn(point_equal(p, (struct point){ 4, 3 })));
    printf("size: %zu = %zu + %zu\n", sizeof p, sizeof p.x, sizeof p.y);
    return 0;
}
Output
struct: x = 3 y = 4
named initializer: x = 3 y = 4
same parts equal: yes
swapped parts equal: no
size: 8 = 4 + 4
  • Verdict: native. A struct is a product by name. An initializer can give the members by position or, with designators, by name.
  • p == q does not compile for structures. A function compares the members.
  • Here the struct has no padding, so its size is the sum of the sizes of its members. ISO C has no empty struct, so it has no unit type.
var t = (3, 4); // parts by position
var (x, y) = t;
Console.WriteLine($"tuple: {t} x = {x} y = {y} Item1 = {t.Item1}");

var p = new Point(3, 4); // parts by name
Console.WriteLine($"record: {p} x = {p.X} y = {p.Y}");
Console.WriteLine("same parts equal: " + Yn(p == new Point(3, 4)));
Console.WriteLine("swapped parts equal: " + Yn(p == new Point(4, 3)));
Console.WriteLine("tuples equal: " + Yn(t == (3, 4)));
Console.WriteLine($"unit: {new Unit()} equal to unit: {Yn(new Unit() == new Unit())}");

static string Yn(bool b) => b ? "yes" : "no";

record Point(int X, int Y);
record Unit;
Output
tuple: (3, 4) x = 3 y = 4 Item1 = 3
record: Point { X = 3, Y = 4 } x = 3 y = 4
same parts equal: yes
swapped parts equal: no
tuples equal: yes
unit: Unit { } equal to unit: yes
  • Verdict: native. A tuple (int, int) is a product by position, and a record is a product by name.
  • Tuples are value types, and == compares their elements. A record class is a reference type, but its == compares the members.
JavaScriptGitHub
const yn = (b) => (b ? "yes" : "no");

const t = [3, 4]; // parts by position
const [x, y] = t;
console.log(`array: x = ${x} y = ${y}`);

const p = { x: 3, y: 4 }; // parts by name
console.log(`object: x = ${p.x} y = ${p.y}`);

const same = { x: 3, y: 4 };
const eq = (a, b) => a.x === b.x && a.y === b.y;
console.log("same parts, ===: " + yn(p === same));
console.log("same parts, by field: " + yn(eq(p, same)));
console.log("swapped parts, by field: " + yn(eq(p, { x: 4, y: 3 })));
Output
array: x = 3 y = 4
object: x = 3 y = 4
same parts, ===: no
same parts, by field: yes
swapped parts, by field: no
  • Verdict: idiom. An object is a product by name, and an array of fixed length is a product by position by convention.
  • === on two objects compares identity, so equal fields are not enough. A function compares the fields.
TypeScriptGitHub
type Size = [width: number, height: number]; // parts by position
type Point = { readonly x: number; readonly y: number }; // parts by name

const yn = (b: boolean): string => (b ? "yes" : "no");

const s: Size = [640, 480];
const [w, h] = s;
console.log(`tuple: width = ${w} height = ${h} length = ${s.length}`);

const p: Point = { x: 3, y: 4 };
const same: Point = { x: 3, y: 4 };
const eq = (a: Point, b: Point): boolean => a.x === b.x && a.y === b.y;
console.log(`object: x = ${p.x} y = ${p.y}`);
console.log("same parts, ===: " + yn(p === same));
console.log("same parts, by field: " + yn(eq(p, same)));
Output
tuple: width = 640 height = 480 length = 2
object: x = 3 y = 4
same parts, ===: no
same parts, by field: yes
  • Verdict: native. A tuple type such as [width: number, height: number] is a product by position, and an object type is a product by name.
  • The labels of a tuple type are for reading only. The values are still read by position.
  • The types do not change equality at run time: === still compares identity.
package main

import (
	"fmt"
	"unsafe"
)

type Point struct{ X, Y int }

func yn(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	p := Point{3, 4}       // fields by position
	q := Point{Y: 4, X: 3} // fields by name
	fmt.Println("struct:", p, "x =", p.X, "y =", p.Y)
	fmt.Printf("named literal: %+v\n", q)
	fmt.Println("same parts equal:", yn(p == q))
	fmt.Println("swapped parts equal:", yn(p == Point{4, 3}))

	var u, v struct{}
	fmt.Println("unit:", u, "equal to unit:", yn(u == v), "size:", unsafe.Sizeof(u))
}
Output
struct: {3 4} x = 3 y = 4
named literal: {X:3 Y:4}
same parts equal: yes
swapped parts equal: no
unit: {} equal to unit: yes size: 0
  • Verdict: native. A struct is a product by name. A composite literal can give the fields by position or by name. Go has no tuple type.
  • == on two structs compares the fields, if every field type is comparable.
  • struct{} has one value and a size of 0, so it is the unit.
RustGitHub
#[derive(Debug, PartialEq)]
struct Point {
    x: i32,
    y: i32,
}

fn yn(b: bool) -> &'static str {
    if b { "yes" } else { "no" }
}

fn main() {
    let t = (3, 4); // parts by position
    let (x, y) = t;
    println!("tuple: {t:?} x = {x} y = {y} t.0 = {}", t.0);

    let p = Point { x: 3, y: 4 }; // parts by name
    println!("record: {p:?} x = {} y = {}", p.x, p.y);
    println!("same parts equal: {}", yn(p == Point { x: 3, y: 4 }));
    println!("swapped parts equal: {}", yn(p == Point { x: 4, y: 3 }));

    let unit = ();
    println!("unit: {unit:?} size: {}", std::mem::size_of::<()>());
}
Output
tuple: (3, 4) x = 3 y = 4 t.0 = 3
record: Point { x: 3, y: 4 } x = 3 y = 4
same parts equal: yes
swapped parts equal: no
unit: () size: 0
  • Verdict: native. A tuple is a product by position, and a struct is a product by name.
  • #[derive(PartialEq)] makes == compare the fields one by one.
  • The unit type () has one value and a size of 0 bytes.
  • Records. A product with named fields. See Record type.
  • Tuples. A product with numbered parts. See Tuple.
  • Sums. The other operation of algebraic data types: one value of one of several cases. See Sum types and Algebraic data type.
  • Arrays. An array of length n with elements of type T is a product of n copies of T. Its parts are numbered at run time, not by the type.
  • Dependent pairs. In a dependent pair, the type of the second part can depend on the value of the first part.2 See Dependent and refinement types.
  • Objects. A class with fields is a product, with methods and often a hidden identity. Two objects with equal fields can still be different objects.

Pitfalls

Comparing two objects by reference

In JavaScript, two objects with the same fields are different values for ===. The comparison checks if both operands are the same object.12

This code runs but gives a wrong answer on purpose.

const p = { x: 3, y: 4 };
const q = { x: 3, y: 4 };
console.log(p === q ? "equal" : "not equal");
Output
not equal

The fix is a function that compares each field, as the JavaScript example file does. Java has the same trap: == on two records compares references, and only equals compares the components.8

Two parts of the same type in the wrong order

A tuple names its parts by position only. When two parts have the same type, the compiler cannot see that they are swapped.

This code runs but gives a wrong answer on purpose.

def area_and_ratio(size: tuple[int, int]) -> str:
    width, height = size
    return f"area {width * height}, width/height {width / height:.2f}"


screen = (1080, 1920)  # the author meant (height, width)
print(area_and_ratio(screen))
Output
area 2073600, width/height 0.56

The area is correct by chance, because multiplication does not depend on the order. The ratio of a 1920 by 1080 screen is 1.78. The fix is a record with named fields, such as Size(width=1920, height=1080), so that each value states which part it is.

Equality of floating-point parts

A product inherits the equality of its parts. In Java, the equals method of a record compares a double component with Double.compare, not with ==.8 So a record that holds NaN is equal to another record that holds NaN, but NaN == NaN is false. Code that compares the fields by hand and code that calls equals can give different answers.

Cost

A product stores each part once, plus any padding between parts.13 Construction writes each part. A projection is a read at a fixed offset, which the compiler knows. Equality compares the parts one by one and stops at the first pair that differs.7 A product that is a value type, such as a C struct, a Go struct, a Rust tuple or a C# tuple, is copied part by part on each assignment. C# tuple types "are value types; tuple elements are public fields".10 A product that is an object on the heap, such as a Java record or a Python dataclass, is copied as a reference.

History

Records came from data processing. "COBOL was the first widespread programming language to support record types."18 Early numeric languages such as FORTRAN and ALGOL 60 did not have them.18 ALGOL W, which first appeared in 1966 and was designed by Niklaus Wirth and Tony Hoare, added "reference to record data types" to ALGOL 60.19 Pascal took its records from ALGOL W, and C provides records as structs.1819 Tuples as product types are a part of the typed functional languages: "Most typed functional programming languages implement tuples directly as product types".20

References

  1. Algebraic data type, Wikipedia, the introduction
  2. Product type, Wikipedia, the introduction
  3. The Rust Programming Language, 5.1 Defining and Instantiating Structs, the introduction
  4. Joel Burget, The algebra (and calculus!) of algebraic data types, Code Words, issue 3, Counting inhabitants
  5. Unit type, Wikipedia, the introduction
  6. The Rust Programming Language, 3.2 Data Types, The Tuple Type
  7. The Go Programming Language Specification, Comparison operators (struct types); Size and alignment guarantees
  8. The Java Language Specification, Java SE 25 Edition, 8.10.3 Record Members (the implicitly declared equals method)
  9. The Python Language Reference, Expressions, 6.10.1 Value comparisons (sequences)
  10. C# language reference, Tuple types, the introduction; Tuple equality
  11. C# fundamentals, Record types, the introduction
  12. MDN Web Docs, Strict equality (===), Description
  13. ISO/IEC 9899:201x, committee draft N1570 (C11), 6.2.5p20; 6.5.9p2 (the operands of ==); 6.7.2.1p8 (no named members), p15 (order and padding)
  14. The Python Standard Library, dataclasses, the introduction
  15. Working Draft, Standard for Programming Language C++ (N4950), [tuple.general], 22.4.1 In general
  16. Kotlin documentation, Data classes, Standard data classes
  17. Working Draft, Standard for Programming Language C++ (N4950), [intro.object], 6.7.2 Object model, paragraph 8 (nonzero size)
  18. Record (computer science), Wikipedia, History
  19. ALGOL W, Wikipedia, the infobox; the introduction
  20. Tuple, Wikipedia, Uses in computer science (the introduction)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/PWHRX6/text.yaml