liveBook · Manning

Union type

As explained in Learn Haskell by Example

A sum type is a data type whose value is one of several alternative constructors, with only one constructor choice present at a time.

A union type, also called a sum type or tagged union, represents one choice from several named alternatives. In Haskell, define the alternatives with data constructors, then pattern match on the selected constructor. section 4.3.1

Listing 4.7 Simple type for distinguishing left from right padding
data PadMode = PadLeft | PadRight

A minimal PadMode type distinguishes left padding from right padding. section 4.3.1

Choosing a padding direction

Use the selected constructor to control the implementation: pad PadLeft 10 "Pad me!" produces " Pad me!", while pad PadRight 10 "Pad me!" produces "Pad me! ". A case expression selects the matching branch. section 4.3.1

Union types provide three practical design benefits:

  • Name each permitted alternative explicitly, such as PadLeft and PadRight. section 4.3.1
  • Keep alternatives mutually exclusive: one constructor is present at a time. section 4.3.1
  • Make each alternative visible to pattern matching and case expressions. section 4.3.1

How Learn Haskell by Example covers it

How deep it goes
Defines constructors and demonstrates pattern matching through a complete padding function, without descending into runtime internals.
Examples
Demonstrates PadMode with PadLeft and PadRight, then applies both choices to padding strings.
What it assumes
Assumes basic Haskell functions and strings while teaching data constructors and pattern matching through padding.
What you can do after
Apply it via Haskell data declarations and case expressions to model and handle a fixed set of alternatives.
How it connects
Connects data declarations with constructors, pattern matching, case expressions, and the Maybe type.

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 Learn Haskell by Example. The section links point to the parts of the book it draws on.