TExcelTAD
Home › Haskell › Haskell GADTs & Type Families

Haskell GADTs & Type Families

This lesson is a short tour of two features that move more checking into the type system: GADTs (generalised algebraic data types) let each constructor choose a more specific result type, and type families are functions that compute types. You won't need them every day, but you will meet them in libraries, and they show how far Haskell's types can go.

The problem: an expression evaluator

Here is a small expression language with an ordinary data type:

haskell · try it yourself
data Expr
  = IntE Int
  | BoolE Bool
  | Add Expr Expr
  | If Expr Expr Expr
  deriving Show

data Value = IntV Int | BoolV Bool deriving Show

eval :: Expr -> Maybe Value
eval (IntE n) = Just (IntV n)
eval (BoolE b) = Just (BoolV b)
eval (Add a b) = case (eval a, eval b) of
  (Just (IntV x), Just (IntV y)) -> Just (IntV (x + y))
  _ -> Nothing                                   -- e.g. adding a Bool
eval (If c t e) = case eval c of
  Just (BoolV True) -> eval t
  Just (BoolV False) -> eval e
  _ -> Nothing

main :: IO ()
main = do
  print (eval (Add (IntE 2) (IntE 3)))
  print (eval (If (BoolE True) (IntE 1) (IntE 0)))
  print (eval (Add (IntE 2) (BoolE True)))        -- nonsense, only caught at run time
Just (IntV 5)
Just (IntV 1)
Nothing

The type Expr happily accepts Add (IntE 2) (BoolE True), so eval must check for nonsense at run time and return a Maybe.

GADTs: constructors with precise types

With the GADTs extension you write each constructor's full type signature. The type parameter a records what the expression evaluates to, and each constructor can fix it:

haskell · try it yourself
{-# LANGUAGE GADTs #-}

data Expr a where
  IntE :: Int -> Expr Int
  BoolE :: Bool -> Expr Bool
  Add :: Expr Int -> Expr Int -> Expr Int
  IsZero :: Expr Int -> Expr Bool
  If :: Expr Bool -> Expr a -> Expr a -> Expr a

eval :: Expr a -> a
eval (IntE n) = n
eval (BoolE b) = b
eval (Add x y) = eval x + eval y
eval (IsZero x) = eval x == 0
eval (If c t e) = if eval c then eval t else eval e

main :: IO ()
main = do
  print (eval (Add (IntE 2) (IntE 3)))
  print (eval (IsZero (Add (IntE 1) (IntE (-1)))))
  print (eval (If (IsZero (IntE 0)) (IntE 10) (IntE 20)))
5
True
10

eval :: Expr a -> a needs no Maybe and no Value wrapper. When GHC matches IntE n, it learns that a is Int in that equation, so returning n is fine. And ill-typed expressions are now rejected at compile time:

haskell · try it yourself
{-# LANGUAGE GADTs #-}

data Expr a where
  IntE :: Int -> Expr Int
  BoolE :: Bool -> Expr Bool
  Add :: Expr Int -> Expr Int -> Expr Int

main :: IO ()
main = print (case Add (IntE 2) (BoolE True) of _ -> "built")
<source>:9:34: error: [GHC-83865]
    * Couldn't match type `Bool' with `Int'
      Expected: Expr Int
        Actual: Expr Bool
    * In the second argument of `Add', namely `(BoolE True)'
      In the expression: Add (IntE 2) (BoolE True)
      In the first argument of `print', namely
        `(case Add (IntE 2) (BoolE True) of _ -> "built")'
  |
9 | main = print (case Add (IntE 2) (BoolE True) of _ -> "built")
  |                                  ^^^^^^^^^^

Type families: functions on types

A type family maps types to types, the way a function maps values to values. A closed type family lists its equations in one place:

haskell · try it yourself
{-# LANGUAGE TypeFamilies #-}

import qualified Data.Map as Map
import qualified Data.Set as Set

-- What element type does a container hold?
type family Elem c where
  Elem [a] = a
  Elem (Set.Set a) = a
  Elem (Map.Map k v) = v

class Container c where
  empty :: c
  insert :: Elem c -> c -> c
  toL :: c -> [Elem c]

instance Container [a] where
  empty = []
  insert = (:)
  toL = id

instance Ord a => Container (Set.Set a) where
  empty = Set.empty
  insert = Set.insert
  toL = Set.toList

fill :: Container c => [Elem c] -> c
fill = foldr insert empty

main :: IO ()
main = do
  print (toL (fill [3, 1, 3, 2] :: [Int]))
  print (toL (fill [3, 1, 3, 2] :: Set.Set Int))
[3,1,3,2]
[1,2,3]

Elem [Int] reduces to Int and Elem (Set Int) to Int, so the same fill works for both containers with the right element type.

Associated types and type-level numbers

A type family can also be declared inside a class (an associated type), and types can be indexed by data lifted to the type level (DataKinds). A classic example is a vector whose length is part of its type, so taking the head of an empty vector is a compile error:

haskell · try it yourself
{-# LANGUAGE GADTs, DataKinds, KindSignatures #-}

data Nat = Z | S Nat

data Vec (n :: Nat) a where
  VNil :: Vec 'Z a
  VCons :: a -> Vec n a -> Vec ('S n) a

vhead :: Vec ('S n) a -> a          -- only accepts non-empty vectors
vhead (VCons x _) = x

vtoList :: Vec n a -> [a]
vtoList VNil = []
vtoList (VCons x xs) = x : vtoList xs

vzip :: Vec n a -> Vec n b -> Vec n (a, b)   -- lengths must match
vzip VNil VNil = VNil
vzip (VCons x xs) (VCons y ys) = VCons (x, y) (vzip xs ys)

main :: IO ()
main = do
  let v = VCons 'a' (VCons 'b' VNil)
      w = VCons 1 (VCons 2 VNil)
  print (vhead v)
  print (vtoList (vzip v w))
'a'
[('a',1),('b',2)]

vhead VNil and vzip on vectors of different lengths don't compile. Note also that vhead needs no [] case: GHC knows it is impossible.

Feature Extension What it gives you
GADTs GADTs constructors that refine the type parameter
Type families TypeFamilies functions from types to types
Data kinds DataKinds use data constructors (Z, S) as types
Kind signatures KindSignatures annotate type variables with kinds (n :: Nat)

Tip: These tools make invalid states unrepresentable, but they also make types harder to read and error messages longer. Use them where a mistake would be costly (interpreters, protocols, database query builders), and keep ordinary code simple.

Test yourself

What does a GADT allow that an ordinary data type does not?

  1. Records
  2. Each constructor can specify a more precise result type
  3. Mutable fields
  4. Infinite constructors

Why can eval :: Expr a -> a return n in the equation eval (IntE n) = n?

  1. a is always Int
  2. Matching IntE tells GHC that a is Int in that equation
  3. GHC converts n
  4. It can't

What is a type family?

  1. A group of related modules
  2. A function that computes types from types
  3. A set of type classes
  4. A data type with many constructors