Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 57 ยท Defining types

Algebraic Data Types

Learn how to define your own Haskell types with data: constructors, sum and product types, records, deriving and pattern matching on constructors.

So far you have used types that Haskell provides: Int, Bool, lists and tuples. The real power of the language appears when you define your own types. A well-chosen type makes illegal states impossible to write, and the compiler then checks that you handle every case.

Haskell types are called algebraic data types (ADTs) because they are built from two operations: choice (a value is one of several alternatives) and combination (a value holds several fields together). This lesson covers both. You should already be comfortable with pattern matching.

Real Haskell is read-only on this site; the runnable blocks use JavaScript objects with a tag to imitate constructors.

Declaring a type with data

HASKELL
data Color = Red | Green | Blue

data introduces a new type called Color. Red, Green and Blue are its data constructors; the vertical bar means "or". Type names and constructor names both start with a capital letter, and they live in different namespaces: a type can reuse its own name for its constructor.

A type with only nullary constructors like this is an enumeration. Bool is defined exactly this way in the standard library:

HASKELL
data Bool = False | True

Constructors with fields

Constructors can carry values. Here is a shape type:

HASKELL
data Shape
  = Circle Double
  | Rectangle Double Double
  | Triangle Double Double Double

Circle takes one Double (the radius), Rectangle takes width and height, and Triangle takes three side lengths. Each constructor is also an ordinary function: Circle :: Double -> Shape, and you can partially apply it, as in map Circle [1, 2, 3].

Sum and product types

The name "algebraic" comes from counting values:

  • A sum type offers alternatives. Color has 3 possible values: it is a sum of three one-value options. Bool has 1 + 1 = 2.
  • A product type combines fields. A pair (Bool, Color) has 2 ร— 3 = 6 possible values.

data declarations mix both: Shape is a sum of three constructors, each of which is a product of its fields.

Two ways to build a type

Sum One of several alternatives, like Red or Green.
Product Several fields together, like width and height.

Real types combine both.

1 / 2

Pattern matching on constructors

You take a value apart by matching its constructors, usually in function clauses or a case expression:

HASKELL
area :: Shape -> Double
area (Circle r)          = pi * r * r
area (Rectangle w h)     = w * h
area (Triangle a b c)    =
  let s = (a + b + c) / 2
  in sqrt (s * (s - a) * (s - b) * (s - c))

describe :: Color -> String
describe c = case c of
  Red   -> "warm"
  Green -> "natural"
  Blue  -> "cool"

If you forget a constructor, GHC can warn with -Wincomplete-patterns (part of -Wall). That warning is one of the biggest benefits of ADTs: when you add | Square Double to Shape, the compiler points to every function that must now handle it.

JS Tagged objects as constructors

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Haskell the compiler checks exhaustiveness for you; in JavaScript the default branch is only a runtime safety net.

Parameterised types

A type can take other types as parameters, written as type variables. The standard Maybe and the tuple-like Pair below are examples:

HASKELL
data Maybe a = Nothing | Just a

data Pair a b = Pair a b

data Tree a = Leaf | Node (Tree a) a (Tree a)

Maybe Int and Maybe String are different types built from one definition. The next lessons treat Maybe and Either in depth; Tree a is recursive and appears later in Recursive Data Types and Trees.

Records: named fields

When a constructor has many fields, positions get hard to remember. Record syntax gives each field a name:

HASKELL
data Person = Person
  { name :: String
  , age  :: Int
  }

This still defines an ordinary constructor Person :: String -> Int -> Person, and additionally creates field accessor functions name :: Person -> String and age :: Person -> Int. You construct values either positionally or by name:

HASKELL
alice = Person { name = "Alice", age = 30 }
bob   = Person "Bob" 25

name alice            -- "Alice"
alice { age = 31 }    -- a copy of alice with age 31

The update syntax alice { age = 31 } does not change alice; it creates a new value, because Haskell values are immutable. Records are covered more fully in Records, newtype and Type Synonyms.

Avoid record fields in types with several constructors unless every constructor has that field. Using an accessor on the wrong constructor fails at runtime with "No match in record selector".

deriving

A new type has no way to be printed or compared. The deriving clause asks GHC to write standard instances for you:

HASKELL
data Color = Red | Green | Blue
  deriving (Show, Eq, Ord, Enum, Bounded)

show Red                  -- "Red"
Red == Blue               -- False
Red < Blue                -- True (constructors are ordered by position)
[minBound .. maxBound] :: [Color]   -- [Red,Green,Blue]
succ Red                  -- Green

Show provides show, Eq provides ==, Ord provides comparison in constructor order, and Enum and Bounded allow ranges and minBound/maxBound on enumerations. See Type Classes: Eq, Ord, Show, Read, Num for the background.

JS An enumeration with a successor

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Designing with types

Good ADT design moves rules from comments into types:

  • Use a sum type instead of a string or number code: data Status = Pending | Shipped | Delivered beats "shipped".
  • Give each alternative exactly the fields it needs. A Circle has no height, so no height field can be wrongly read.
  • Prefer types that cannot represent invalid combinations. Instead of a record with isLoggedIn :: Bool and userName :: Maybe String, use data Session = Guest | LoggedIn String.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In data Shape = Circle Double | Rectangle Double Double, what is Rectangle?

    Rectangle is a constructor with type Double -> Double -> Shape.
  2. 2. How many values does the type (Bool, Color) have if Color has three constructors?

    Product types multiply: 2 x 3 = 6.
  3. 3. What does alice { age = 31 } do?

    Record update builds a modified copy; Haskell values are immutable.
  4. 4. Which deriving clause lets you write Red < Blue?

    Ord provides comparison operators; derived Ord orders constructors by their position in the declaration.
  5. 5. What is the main benefit of -Wincomplete-patterns with sum types?

    When you add a constructor, GHC can point to every pattern match that no longer covers all cases.

Summary

  • data defines a new type with one or more constructors separated by |.
  • Sum types offer alternatives; product types hold several fields; data combines both.
  • Constructors are functions, and you take values apart by pattern matching on them.
  • Record syntax names fields and gives you accessors and update syntax, with immutable copies.
  • deriving generates Show, Eq, Ord, Enum and Bounded instances for you.
  • Design types so that invalid states cannot be written.

Next: Records, newtype and Type Synonyms.