liveBook · Manning

Union type

As explained in Functional Design and Architecture: Examples in Haskell

A sum type represents a value that can be one of several alternative constructors or variants.

A union type, also called a sum or variant type, models a value that may take one of several named forms. It is a building block of algebraic data types, which combine alternative forms with product types such as tuples or records to represent a domain. section 2.1.2

Use variants when one domain concept has distinct cases with different data. This makes the permitted actions explicit instead of forcing unrelated fields into a single broad structure. section 2.1.2

Different kinds of actions

Actions can send money, invite people to a party, or schedule a meeting. Each variant carries only the information it needs: a recipient and amount, attendees, or a person and time. section 2.1.2

data Actions
 = SendMoney { to :: Person, amount :: Money }
 | InviteToParty { attendees :: List Person }
 | ScheduleMeeting { with :: Person, when :: DateTime }

Inspect a declaration with three alternatives and variant-specific record fields. section 2.1.2

How Functional Design and Architecture: Examples in Haskell covers it

How deep it goes
Defines sum types as ADT components and illustrates variant declarations without detailing pattern matching or representation internals.
Examples
Illustrates an Actions type with SendMoney, InviteToParty, and ScheduleMeeting variants.
What you can do after
Evaluate/understand how alternative variants can encode different forms of a domain action.
How it connects
Connects union types to algebraic data types, product types, tuples, records, recursion, and domain models.

Also explained in

Compare how 10 books explain union type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.