Course map
Haskell // 09

Algebraic data types

Read

data

The data keyword defines a new type by listing its constructors. A type with several constructors is a sum ("one of these"); a constructor with fields is a product ("all of these").

data Shape
  = Circle Double
  | Rect Double Double
  deriving (Show, Eq)

area :: Shape -> Double
area (Circle r) = 3.14159 * r * r
area (Rect w h) = w * h

Circle 2.0 and Rect 3 4 are values of type Shape. Pattern matching takes them apart. deriving (Show, Eq) asks the compiler to write show and == for you.

You have already met a sum type: the Action of a miso app is one. Each constructor is one thing that can happen.

01 / 05