data: sum types

One of several

Several constructors separated by a vertical bar make a sum type: a value is exactly one of the alternatives. Each constructor may carry its own fields:

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

A Shape is a circle, a rectangle, or a triangle, and nothing else. There is no way to build a shape that is half of one and half of another, which is what makes the type safe.

Match every branch

A function over a sum type names one equation per constructor. The compiler warns when one is missing, so the match stays complete as the type grows:

area :: Shape -> Double area (Circle r) = pi * r * r area (Rect w h) = w * h area (Triangle b h) = b * h / 2

Note that each constructor carries exactly the fields its formula needs. A circle has no width, and the type does not pretend otherwise.

Replacing booleans

Two booleans give four states, and usually only three of them are legal. A sum type makes the illegal state unrepresentable:

-- four states, one of them nonsense load :: Bool -> Bool -> String load dirty saved | dirty && saved = "dirty and saved" -- nonsense | dirty = "dirty" | saved = "saved" | otherwise = "new" -- three states, all of them real data State = Idle | Loading | Done String

The second version also attaches the result to the state that needs it. With two booleans, a caller has to remember that True True means finished and which variable holds the payload.

Types that grow

Adding a constructor later breaks every function that matches on the type, and that is the point. The compiler hands you the list of places to update:

data Shape = Circle Double | Rect Double Double | Triangle Double Double | Polygon [(Double, Double)] -- now area is non-exhaustive until Polygon is handled

A wildcard branch would have hidden that work. Avoid _ -> on your own sum types and let the warning be your checklist.

The code on this page was run with GHC 9.10.3 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev