Tagged union¶
Represent a value as exactly one member of a fixed family of payload alternatives together with a discriminator that records the active alternative and governs safe elimination or pattern matching.
Core Idea¶
A tagged union, also called a discriminated union or variant, is a sum-like data representation whose value contains one alternative payload and a tag identifying which alternative is active.[1] Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family The abstraction is therefore identified by a declared carrier, a transformation or constraint over that carrier, and an invariant that tells an analyst whether the named structure is genuinely present.
The load-bearing residual is not the broad topic of computer science. It is the closed alternative family plus active-case discriminator and typed elimination rule, not merely overlapping storage or the broad idea of an abstract data type. That residual remains recognizable when examples, notation, scale, or implementation change, but it disappears if the active member must be inferred from raw bits, multiple alternatives are simultaneously active, the tag can contradict the payload without a validity rule, or an open subtype family is substituted for a closed sum. This gives the entry an operational identity rather than merely a historical label.
A useful analysis keeps three layers separate. The constitutive layer says what must be true: the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation. The evidential layer asks what observation or proof warrants the claim: list the alternatives, type each payload, identify how the active case is encoded, verify construction preserves tag-payload agreement, and check that elimination dispatches only to the matching payload interpretation. The use layer asks what reasoning becomes available once the identity is established: modeling alternatives, recursive syntax trees, option and result types, protocol messages, and state machines while localizing invalid-case handling and enabling exhaustiveness checks. Conflating the layers is the most common source of scope inflation.
Structural Signature¶
- Carrier: a finite family of alternative payload types or record shapes and a value inhabiting exactly one labeled alternative
- Inputs or antecedent state: variant labels, payload type for each label, an injection or constructor, a stored or logical discriminator, and case-analysis operations
- Constitutive operation: Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family
- Invariant: the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation
- Recognition test: list the alternatives, type each payload, identify how the active case is encoded, verify construction preserves tag-payload agreement, and check that elimination dispatches only to the matching payload interpretation
- Output or consequence: modeling alternatives, recursive syntax trees, option and result types, protocol messages, and state machines while localizing invalid-case handling and enabling exhaustiveness checks
- Failure boundary: the active member must be inferred from raw bits, multiple alternatives are simultaneously active, the tag can contradict the payload without a validity rule, or an open subtype family is substituted for a closed sum
What It Is Not¶
- It is not the whole field of computer science. The field contains many questions and methods that do not instantiate Tagged union.
- It is not its most familiar example. A result type has constructors Ok carrying a value and Error carrying an error object; its tag selects which payload is meaningful. exhibits the structure, but the example is evidence for the abstraction rather than its definition.
- It is not the neighboring catalog concept Abstract Data Type. An abstract data type specifies behavior behind an implementation boundary; a tagged union specifies an alternative-bearing value form and discriminator, and can be exposed rather than abstract.
- It is not a claim that every boundary case has one uncontested classification. Some high-level sum types have no separately addressable runtime tag because representation optimization derives or erases it, yet their semantics still provide labeled injections and disjoint case elimination
- It is not an unrestricted metaphor for any process that seems similar. Outside computer science, the vocabulary and validity conditions do not transfer literally.
Scope of Application¶
Tagged union belongs to computer science and is useful where the analyst can specify a finite family of alternative payload types or record shapes and a value inhabiting exactly one labeled alternative, then evaluate the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation. The scope is broad within that domain but bounded by the need for the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation. The reference identity is semantic rather than one memory layout; representation optimizations qualify only when they preserve the active-case and typed-elimination contract.[2]
- Definition and recognition. Determine whether a proposed instance satisfies the constitutive conditions rather than merely sharing terminology.
- Construction or evolution. Track how variant labels, payload type for each label, an injection or constructor, a stored or logical discriminator, and case-analysis operations are converted, constrained, or organized by Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family.
- Comparison. Compare instances using number of variants, payload arity, recursive occurrence, runtime representation, discriminant width, exhaustiveness, openness, layout, and invalid-state policy, without treating convenience measures as the definition.
- Boundary analysis. Diagnose cases where Some high-level sum types have no separately addressable runtime tag because representation optimization derives or erases it, yet their semantics still provide labeled injections and disjoint case elimination and state which convention or theorem controls the decision.
- Downstream reasoning. Use the established identity to support modeling alternatives, recursive syntax trees, option and result types, protocol messages, and state machines while localizing invalid-case handling and enabling exhaustiveness checks while preserving the assumptions under which the inference is valid.
Clarity¶
The abstraction clarifies a crowded vocabulary by making the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation the center of the account. A claim should name the carrier, the governing operation or relation, the applicable assumptions, and the recognition test. A bare label is insufficient because tagged union, discriminated union, variant, sum type, and enum overlap differently across languages, while union type can also denote an untagged or structural type operation. The disciplined statement is: given variant labels, payload type for each label, an injection or constructor, a stored or logical discriminator, and case-analysis operations, the structure counts as Tagged union exactly when the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation.
This format also separates identity from measurement. Memory size and branch cost depend on alignment, payload maxima, compiler optimization, and target ABI; they are implementation properties rather than the definition. Measurements can be noisy, implementations can approximate, and proofs can use equivalent characterizations; none of those facts licenses changing the object being measured. When reports disagree, first check scope and convention, then data or proof, and only then interpret the disagreement as substantive.
Manages Complexity¶
Without the abstraction, an analyst must reason directly over many local details: the carrier roles, admissibility assumptions, competing conventions, derived invariants, boundary cases, and proof or validation obligations specific to Tagged union. Tagged union compresses them into the roles in the structural signature. That compression permits comparison across instances without erasing the variables that determine validity. It also exposes which details may be varied safely and which are constitutive.
The compression has a price. A single label can hide language-level sum types, variant records, manually tagged storage unions, nested sums, recursive algebraic data types, niche-optimized layouts, and serialized message formats. Good use therefore carries a small declaration of assumptions alongside the name. The abstraction manages complexity when it reduces the state space of the question while keeping the failure boundary visible; it mismanages complexity when the label substitutes for that boundary analysis.
Abstract Reasoning¶
- Identify the carrier. State what the elements, states, objects, or observations are: a finite family of alternative payload types or record shapes and a value inhabiting exactly one labeled alternative. Reject examples whose alleged carrier belongs to a different problem.
- Lock the constitutive rule. Express the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation independently of one notation or implementation. This step prevents the canonical example from becoming the definition.
- Derive consequences. From the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation, infer modeling alternatives, recursive syntax trees, option and result types, protocol messages, and state machines while localizing invalid-case handling and enabling exhaustiveness checks. Record each assumption used so that a later change of setting does not silently preserve an invalid conclusion.
- Test adversarial cases. Examine Some high-level sum types have no separately addressable runtime tag because representation optimization derives or erases it, yet their semantics still provide labeled injections and disjoint case elimination and an untagged C union whose consumer guesses the active member from context is not a tagged union. A robust identity explains why the first is convention-sensitive and why the second is outside the class.
- Compare and refine. Use number of variants, payload arity, recursive occurrence, runtime representation, discriminant width, exhaustiveness, openness, layout, and invalid-state policy to compare legitimate instances, and refine the model when discrepancies reflect hidden variation rather than failure of the abstraction itself.
Knowledge Transfer¶
Knowledge transfers strongly among subfields of computer science because they reuse a finite family of alternative payload types or record shapes and a value inhabiting exactly one labeled alternative, Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family, and list the alternatives, type each payload, identify how the active case is encoded, verify construction preserves tag-payload agreement, and check that elimination dispatches only to the matching payload interpretation. A theorem, diagnostic, or modeling warning can travel when those roles remain literal. For example, the distinction between constitutive identity and a convenient observable transfers from A result type has constructors Ok carrying a value and Error carrying an error object; its tag selects which payload is meaningful. to A low-level protocol record stores an explicit message-kind field next to a union of case-specific layouts..[3]
Transfer outside the home domain is weaker. The skeletal pattern—pair one of several mutually exclusive payload forms with an unambiguous selector and eliminate by selector-governed branching—may suggest an analogy, but the domain-specific mechanisms, admissible evidence, and consequences do not come along automatically. The safe transfer procedure maps each role explicitly, checks the invariant again, and refuses the name when only a superficial resemblance remains.
Examples¶
Canonical¶
A result type has constructors Ok carrying a value and Error carrying an error object; its tag selects which payload is meaningful. Construction produces exactly one labeled injection, and a case expression branches on the tag before binding the payload at the corresponding type; a missing branch is detectable in languages with exhaustiveness analysis. This example is canonical because every role can be inspected: the carrier is a finite family of alternative payload types or record shapes and a value inhabiting exactly one labeled alternative; the operative rule is Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family; the invariant is the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation; and the result supports modeling alternatives, recursive syntax trees, option and result types, protocol messages, and state machines while localizing invalid-case handling and enabling exhaustiveness checks.[1] Changing incidental notation or scale leaves the structure intact, while removing the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation destroys the classification.
Mapped back: a finite family of alternative payload types or record shapes and a value inhabiting exactly one labeled alternative → Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family → the discriminator and payload remain consistent so that the active case can be recovered without guessing from overlapping representation → modeling alternatives, recursive syntax trees, option and result types, protocol messages, and state machines while localizing invalid-case handling and enabling exhaustiveness checks
Applied / In Practice¶
A low-level protocol record stores an explicit message-kind field next to a union of case-specific layouts. It qualifies only if validation keeps the kind field consistent with the selected layout; an unchecked C union alone is not tagged. The applied case is not licensed merely by vocabulary. It qualifies because the same recognition test—list the alternatives, type each payload, identify how the active case is encoded, verify construction preserves tag-payload agreement, and check that elimination dispatches only to the matching payload interpretation—can be run and because the same failure boundary—the active member must be inferred from raw bits, multiple alternatives are simultaneously active, the tag can contradict the payload without a validity rule, or an open subtype family is substituted for a closed sum—remains meaningful.[2] The case also shows why practical outputs should report assumptions, resolution, and uncertainty instead of a naked label.
Mapped back: declared instance → recognition test → boundary check → qualified use
Structural Tensions¶
- T1: Axiomatic identity vs. operational recognition. The defining conditions may be exact while empirical or computational recognition is approximate. Neither pole can be removed without changing the analytical task. Diagnostic: Can the reviewer state both the exact condition and the evidence used to infer it?
- T2: Local roles vs. global consequence. The mechanism is enacted through local relations, but the abstraction is usually valued for a global classification or prediction. Neither pole can be removed without changing the analytical task. Diagnostic: Does the claimed global result actually follow from the declared local conditions?
- T3: Ideal form vs. finite representation. Theory states a clean invariant while data structures, measurements, or proofs expose only finite representations. Neither pole can be removed without changing the analytical task. Diagnostic: Would increasing resolution converge toward the same classification?
- T4: Canonical convention vs. legitimate variants. A standard formulation supports communication, while variants may preserve the same core under changed assumptions. Neither pole can be removed without changing the analytical task. Diagnostic: Which role is invariant across variants, and which convention-specific conclusion changes?
- T5: Compression vs. hidden assumptions. The name compresses a complex argument but can conceal prerequisites. Neither pole can be removed without changing the analytical task. Diagnostic: Can each downstream inference be traced to an explicit assumption?
- T6: Autonomous residual vs. reduction to catalog neighbors. The candidate uses broader structures but adds an identity-bearing residual. Neither pole can be removed without changing the analytical task. Diagnostic: After subtracting the proposed parent and named neighbors, does the constitutive residual still support independent diagnostics?
Structural–Framed Character¶
The entry is structurally mixed but domain-framed. Its portable skeleton is pair one of several mutually exclusive payload forms with an unambiguous selector and eliminate by selector-governed branching. Its identity-bearing terms—variant, constructor, injection, discriminator, payload, pattern match, exhaustiveness, sum type, and union layout—derive their meaning from computer science and cannot be replaced by generic systems language without losing the tests that distinguish valid from invalid instances.
This mixed character explains why the abstraction is reusable inside the domain yet does not meet the Prime bar. The structure organizes reasoning, but its claims still depend on domain-specific objects, evidence, and intervention semantics.
Structural Core vs. Domain Accent¶
The structural core consists of a carrier, Construction couples a label with a payload of the label's declared type; elimination inspects the label and exposes the correspondingly typed payload, while exhaustive case analysis accounts for the closed alternative family, a recognition invariant, and a consequence. That skeleton may resemble patterns elsewhere, especially pair one of several mutually exclusive payload forms with an unambiguous selector and eliminate by selector-governed branching. The domain accent is not decorative: variant, constructor, injection, discriminator, payload, pattern match, exhaustiveness, sum type, and union layout determine what counts as an admissible carrier, a valid transition, and successful evidence.
The abstraction therefore remains domain-specific. A cross-domain reuse that preserves only words such as 'balance,' 'cut,' 'sequence,' 'loss,' or 'simulation' is metaphor. Literal transfer requires the original role structure and diagnostics, which in this case remain anchored in computer science.
Instantiates / Related Primes¶
The proposed strict upward parent is prime:data_structure. The candidate literally arranges label and alternative payload information to make construction and case selection safe and efficient; that is a Data Structure specialization with a fixed sum-type invariant. This is a proposal-only workspace relationship: the accepted Prime supplies a genuinely instantiated structural prerequisite or superclass, while Tagged union adds domain-specific constraints.
The entry does not collapse into that parent because the closed alternative family plus active-case discriminator and typed elimination rule, not merely overlapping storage or the broad idea of an abstract data type It also declines a nearby thematic catalog node: the neighbor does not literally subsume the constitutive identity of Tagged union. This explicit assert-and-decline pattern keeps the proposed DAG narrow and prevents a merely thematic edge.
The prospective workspace queue contains one strict upward edge to prime:data_structure. No live DAG mutation is authorized.
Relationships to Other Abstractions¶
Current abstraction Tagged union Domain-specific
Parents (1) — more general patterns this builds on
-
Tagged union is a kind of Data Structure Prime
The proposed strict upward parent is
prime:data_structure.The candidate literally arranges label and alternative payload information to make construction and case selection safe and efficient; that is a Data Structure specialization with a fixed sum-type invariant. This is a proposal-only workspace relationship: the accepted Prime supplies a genuinely instantiated structural prerequisite or superclass, while Tagged union adds domain-specific constraints. The entry does not collapse into that parent because the closed alternative family plus active-case discriminator and typed elimination rule, not merely overlapping storage or the broad idea of an abstract data type It also declines a nearby thematic catalog node: the neighbor does not literally subsume the constitutive identity of Tagged union. This explicit assert-and-decline pattern keeps the proposed DAG narrow and prevents a merely thematic edge. The prospective workspace queue contains one strict upward edge toprime:data_structure. No live DAG mutation is authorized.
Hierarchy path (1) — routes to 1 parentless root
- Tagged union → Data Structure → Trade-offs → Constraint
Neighborhood in Abstraction Space¶
Tagged union sits in a sparse region of the domain-specific corpus (64th percentile for distinctiveness): few abstractions share its structure, so a faithful description tends to retrieve it precisely.
Family — Syntax, Rewriting & Declarative Form (41 abstractions)
Nearest neighbors
- Alternative semantics — 0.86
- Identity transform — 0.86
- Binary classification — 0.85
- Mutual recursion — 0.85
- Index set — 0.85
Computed from structural-signature embeddings · 2026-09-08
Not to Be Confused With¶
- Untagged union. Overlaps storage without an intrinsic active-case discriminator.
- Union type. May mean a set-theoretic or structural type union without labeled injections or a runtime tag.
- Enumeration. Carries one label but ordinarily no case-specific payload.
- Subtype polymorphism. Selects among an open or extensible class hierarchy rather than a fixed sum of alternatives.
References¶
[1] Benjamin C. Pierce, Types and Programming Languages, MIT Press, 2002, sections 11.9–11.10 on sums and variants, ISBN 978-0-262-16209-8. registry ↩a ↩b
[2] Robert Harper, Practical Foundations for Programming Languages, 2nd ed., Cambridge University Press, 2016, Part IV on finite data types, DOI 10.1017/CBO9781316576892. registry ↩a ↩b
[3] Lean Reference Manual, 'Sum Types,' documenting labeled left/right injections and case distinction, Lean project documentation, accessed 2026-08-29. registry ↩