🎓 A1Learner
🔍
0 of 47 lessons completed

Haskell Closed Type Families

A closed type family is a type family whose equations are fixed in one place. No new equations can be added later.

The first equation matches an integer type

Pick maps Int to String. A value of that result type is a string.

{-# LANGUAGE TypeFamilies #-}
type family Pick a where
  Pick Int = String
  Pick a = Bool
intPick :: Pick Int
intPick = "picked"
main :: IO ()
main = putStrLn intPick

The catch-all equation matches any other type

Bool does not match the Int equation. It falls through to the catch-all equation, which gives Bool.

{-# LANGUAGE TypeFamilies #-}
type family Pick a where
  Pick Int = String
  Pick a = Bool
boolPick :: Pick Bool
boolPick = True
main :: IO ()
main = print boolPick

Order decides which equation wins

Int matches the first equation, not the catch-all. A character type matches only the catch-all.

{-# LANGUAGE TypeFamilies #-}
type family Pick a where
  Pick Int = String
  Pick a = Bool
intPick :: Pick Int
intPick = "picked"
charPick :: Pick Char
charPick = False
main :: IO ()
main = do
  putStrLn intPick
  print charPick

Example

{-# LANGUAGE TypeFamilies #-}
type family Pick a where
  Pick Int = String
  Pick a = Bool
intPick :: Pick Int
intPick = "picked"
boolPick :: Pick Bool
boolPick = True
charPick :: Pick Char
charPick = False
main :: IO ()
main = do
  putStrLn intPick
  print boolPick
  print charPick

Key points

  • Closed type family: a type family with all its equations written together in its definition.
  • The compiler tries the equations in order and uses the first match.
  • A closed family is a fixed list, not an open list that later code can extend.
  • Use a catch-all equation last to handle every remaining type.
  • A specific equation must come before a general equation that would also match.

In this example, Pick is defined with an Int equation first and a catch-all equation last. Int takes the first equation, while Bool and Char fall through to the catch-all. The prints show a string, a boolean true, and a boolean false in that order.

Note

A closed family needs the TypeFamilies language extension.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which statement about a closed family is true?