liveBook · Manning

Union type

As explained in F# in Action: A Revised Edition of Get Programming with F#

A discriminated union is an F# type whose values are selected from a fixed set of named cases, each potentially carrying different data.

A discriminated union models a choice: a value is exactly one of a fixed set of named cases. Use it for an OR relationship, such as a customer's contact method. Records and tuples model AND relationships, where their fields exist together. Unlike an enum, each union case can carry the data that particular choice needs. section 8.3 section 8.3.1

Listing 8.8 Our first discriminated union
type ContactMethod =                                 #1
    | Email of address:string                        #2
    | Telephone of country:string * number:string    #3
    | Post of
        {|                                           #4
            Line1 : string
            Line2 : string
            City : string
            Country : string
        |}

The ContactMethod declaration shows three cases with different payload shapes: an email address, a country-and-number tuple, and postal details in an anonymous record. section 8.3.1

Construct and use a contact method

A smaller version makes the construction and matching rules easy to try: type ContactMethod = | Email of address:string | Telephone of country:string * number:string let describe contact = match contact with | Email address -> $"Email {address}" | Telephone (country, number) -> $"Call {country}-{number}" describe (Telephone ("UK", "020-8123-4567")) Both cases produce a ContactMethod value, not separate Email and Telephone types. Pattern matching selects a case and makes only its associated data available. section 8.3.1 section 8.3.2

Cases can hold primitives, tuples, records, anonymous records, or other unions. For example, an SMS contact method can hold a telephone-number union whose cases are Local and International. This lets a domain model combine choices with groups of required fields. Prefer explicit match branches: if a new case goes unhandled, the compiler can warn about the missing case; a broad wildcard may hide it. section 8.3.4 section 8.4.3

Union cases also make errors specific. Instead of returning an undifferentiated error string, validation can return cases such as EmptyCustomerId or InvalidCustomerIdFormat. Separate error unions can represent each validation function's possible failures, then be combined into a larger error type. section 9.2.3

A single-case union can distinguish a validated value from an ordinary string. Keep behavior in functions that operate on the data when that makes new operations easier to add. Adding a new union case is a different trade-off: existing matches may need updating. In C#, F# unions appear as a class hierarchy, but C# matching does not provide the same exhaustiveness check. section 14.1.1 section 8.3.2 section 11.2.1

How F# in Action: A Revised Edition of Get Programming with F# covers it

How deep it goes
Works through case declarations, construction, nested payloads, and exhaustive matching without detailing runtime internals.
Examples
Uses customer contact methods, nested SMS numbers, and loan decisions to illustrate cases.
What it assumes
Builds on records, tuples, and pattern matching while introducing union-case syntax through a customer example.
What you can do after
Build it from scratch to represent domain choices, then pattern-match their case-specific data and heed missing-case warnings.
How it connects
Connects unions to records, tuples, pattern matching, Result, and typed validation errors.

Also explained in

Compare how 11 books explain union type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of F# in Action: A Revised Edition of Get Programming with F#. The section links point to the parts of the book it draws on.