Product Type
Overview
A Product type is a composite data type formed by combining multiple values together, where the total number of possible values is the product of the possibilities of its components.
It models data where all components exist simultaneously.
What Is a Product Type?
If a type A has m possible values and type B has n possible values, then:
A × B → m × n possible values
Common examples of product types include:
- Records / Structs
- Tuples
- Objects with fields
How It Works
A product type stores:
- All its component values at the same time
- Each component independently
- Memory is allocated for each field, and access is done by position or name.
Example
Pseudocode
type Point = (Integer, Integer)
p = (3, 5)
If each integer has 100 possible values, Point has 10,000 possible values.
Real-world Analogy
A product type is like a coordinate. You need both the x and y values together to describe a location 📍.
Common Operations
- Construction
- Destructuring
- Field access
- Comparison (component-wise)
Time and Space Complexity
- Space: O(n), where n is number of components
- Access: O(1)
Use Cases
- Representing structured data
- Modeling entities
- Function inputs and outputs
- Geometry and vectors
Advantages
- Strong structure
- Clear semantics
- Easy composition
Limitations
- Fixed structure
- Can grow large with many fields
- Less flexible than sum types
Product Type vs Sum Type
| Aspect | Product Type | Sum Type |
|---|---|---|
| Structure | All fields present | One of many variants |
| Examples | Struct, Tuple | Union, Tagged Union |
| Data modeling | Composition | Choice |