In the last section, you learned how to work with a wide variety of type level data, including natural numbers, strings, and data structures like lists and tuples. Having all of this data available at the type level is of limited use without being able to write computations to transform the data. In Haskell, we can build type level functions using a feature called Type Families .

Type families are conceptually straightforward. A type family is a function that accepts some types and returns a type, just like a term level function accepts some term level values and returns a value. Unlike term level functions, there are different “varieties” of type family we’ll look at. Although each of these sorts of type family ultimately acts as a type level function, the way we write them and the reasons we use them vary. In this section, we’ll start by looking at the most commonly used sort of type family: associated type families , which let us associate a type family with a particular type class, and give an alternative to functional dependencies that’re often easier to use. Next, we’ll look at open type families. These are similar to associated type families, but can be used outside of a type class. Finally, we’ll look at closed type families. Closed type families are more limited than associated and open type families, since users can’t add new instances in their own code. This limitation also makes closed type families more useful for type level programming, since we’re able to use them more easily for writing general purpose computations.

Associated Type Families

Associated type families are the most common way that type families are used. Before we dive into understanding exactly what they are and how they work, let’s look at a short example. Imagine that we’re writing a library for working with shell commands where we would like to represent each supported shell command as its own type. For example, imagine that we have two types, ListDirectory and Grep , to represent the ls and grep commands:

​  ​ newtype ​ ​ ListDirectory ​ =
​  ​ ListDirectory ​ { listDirectoryName :: ​ FilePath ​ }
​  
​  ​ data ​ ​ Grep ​ =
​  ​ Grep ​ { grepMatch :: ​ String ​, grepFiles :: [​ String ​]}

One way we might want to approach building this library is to define a type class, ShellCommand , for types that can be run at the command line. This will let us encapsulate both the way we generate command line arguments from a particular command, as well as how we handle the output generated by the shell. How should we define it? We might start with something like this:

​  ​ class ​ ​ ShellCommand ​ cmd ​ where ​
​  runCmd ::
​  ​ Monad ​ m => cmd -> (​ String ​ -> [​ String ​] -> m ​ String ​) -> m ​ String ​

In this example, our class defines a single function runCmd that will take a command, and a function from an executable path and list of arguments to some output, and we will return the output. Unfortunately, this isn’t a very good abstraction since we’re essentially returning whatever output the shell generates unmodified. It would be better if we could return something that better represented the particular output of each command, but then we’re faced with a different problem: what type should we return?

Using what you’ve learned in this book so far, there are a couple of solutions you might see. One option would be to create a sum type, ShellCommandOutput , and add a constructor for each type of output that we wanted to parse. This would work as long as we only wanted to support a finite number of shell commands, but it’s not extensible. Any time we wanted to add a new command, we’d need to add a new constructor to ShellCommandOutput .

A second option would be to use a multi-parameter type class. Since the type of output that’s generated depends on the command that’s run, we can use functional dependencies to define the relationship. Let’s take a look at a complete example using functional dependencies as a starting point.

System.Process

| images/aside-icons/info.png | Remember that the System.Process module comes from the process library that you used earlier in the Local System chapter. |

​  ​ {-# LANGUAGE FunctionalDependencies #-} ​
​  ​ {-# LANGUAGE FlexibleInstances #-} ​
​  
​  ​ module ​ ​ ShellCommandFunDeps ​ ​ where ​
​  ​ import ​ ​ System.Process ​ (​ readProcess ​)
​  
​  ​ class ​ ​ ShellCommand ​ cmd cmdOutput | cmd -> cmdOutput ​ where ​
​  runCmd ::
​  ​ Monad ​ m =>
​  cmd ->
​  (​ String ​ -> [​ String ​] -> m ​ String ​) ->
​  m cmdOutput
​  
​  ​ newtype ​ ​ ListDirectory ​ =
​  ​ ListDirectory ​ { listDirectoryName :: ​ FilePath ​ }
​  
​  ​ instance ​ ​ ShellCommand ​ ​ ListDirectory ​ [​ FilePath ​] ​ where ​
​  runCmd (​ ListDirectory ​ dir) run =
​  lines <$> run ​ "ls" ​ [​ "-1" ​, dir]
​  
​  ​ data ​ ​ Grep ​ =
​  ​ Grep ​ { grepMatch :: ​ String ​ , grepFiles :: [​ String ​]}
​  
​  ​ data ​ ​ GrepMatch ​ = ​ GrepMatch ​
​  { grepMatchingFileName :: ​ FilePath ​
​  , grepMatchingLineNumber :: ​ Int ​
​  , grepMatchingLineContents :: ​ String ​
​  } ​ deriving ​ (​ Eq ​, ​ Show ​)
​  
​  parseGrepResponse :: [​ String ​] -> [​ GrepMatch ​]
​  parseGrepResponse = map parseLine
​  ​ where ​
​  parseLine responseLine =
​  ​ let ​
​  (fileName, rest) = span (/= ​ ':' ​) responseLine
​  (matchNumber, rest') = span (/= ​ ':' ​) $ tail rest
​  contents = tail rest'
​  ​ in ​ ​ GrepMatch ​ fileName (read matchNumber) contents
​  
​  ​ instance ​ ​ ShellCommand ​ ​ Grep ​ [​ GrepMatch ​] ​ where ​
​  runCmd (​ Grep ​ match grepFiles) run =
​  parseGrepResponse . fixResponses . lines <$>
​  run ​ "grep" ​ (​ "-n" ​ : match : grepFiles)
​  ​ where ​
​  fixResponses :: [​ String ​] -> [​ String ​]
​  fixResponses responseLines =
​  ​ case ​ grepFiles ​ of ​
​  [fname] -> (​ \ ​l -> fname <> ​ ":" ​ <> l) <$> responseLines
​  ​ _ ​ -> responseLines
​  
​  ​ data ​ ​ Pipe ​ a r b r' = ​ Pipe ​ a (r -> b)
​  ​ instance ​ (​ ShellCommand ​ a r, ​ ShellCommand ​ b r') =>
​  ​ ShellCommand ​ (​ Pipe ​ a r b r') r' ​ where ​
​  runCmd (​ Pipe ​ a mkB) run = ​ do ​
​  result <- runCmd a run
​  runCmd (mkB result) run
​  
​  grepFilesInDirectory ::
​  ​ String ​ ->
​  ​ FilePath ​ ->
​  ​ Pipe ​ ​ ListDirectory ​ [​ FilePath ​] ​ Grep ​ [​ GrepMatch ​]
​  grepFilesInDirectory match dir =
​  ​ Pipe ​ (​ ListDirectory ​ dir) $
​  ​ Grep ​ match . map (​ \ ​fname -> dir <> ​ "/" ​ <> fname)
​  
​  runShellCommand :: ​ ShellCommand ​ cmd r => cmd -> ​ IO ​ r
​  runShellCommand cmd =
​  runCmd cmd (​ \ ​cmdName args -> readProcess cmdName args ​ "" ​)

As you can see in this example, using functional dependencies works well enough for individual commands like ListDirectory and Grep , but it starts to show some rough edges when we begin to compose our commands with Pipe . The extra type parameters add noise and reduce the ergonomics, but a bigger problem is that writing a function like grepFilesInDirectory requires that we write out the specific output type of our intermediate commands. That means we’ll need to change the type signature if we decide to refactor our commands to change the types they use internally. Worse, refactoring our library might require the users to change their code because of an implementation detail in how we represent some of our commands.

TypeFamilies

| images/aside-icons/info.png | The TypeFamilies extension has been available since GHC 6.8.1. This extension isn’t enabled by default in GHC2021 or Haskell2010 so you’ll need to enable it manually. This is a safe extension that shouldn’t cause problems with any existing code. |

Associated type families are a useful alternative to multi-param type classes with functional dependencies in circumstances like this, because they allow us to write a function from our input type to the output type as a type level function that is embedded directly into our type class. To use associated type families we’ll need to enable the TypeFamilies extension. With this extension enabled, we can add an associated type family to our type class with the type keyword. Let’s look at an example of a type family in our ShellCommand class:

​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE RecordWildCards #-} ​
​  
​  ​ module ​ ​ ShellCommand ​ ​ where ​
​  ​ import ​ ​ Data.Kind ​
​  ​ import ​ ​ System.Process ​ (​ readProcess ​)
​  
​  ​ class ​ ​ ShellCommand ​ cmd ​ where ​
​  ​ type ​ ​ ShellOutput ​ cmd :: ​ Type ​
​  runCmd ::
​  ​ Monad ​ m =>
​  cmd ->
​  (​ String ​ -> [​ String ​] -> m ​ String ​) ->
​  m (​ ShellOutput ​ cmd)

In this example, ShellOutput is an associated type family that we use to map a particular instance of ShellCommand to the type of output that will be generated by running the command. In this example, ShellOutput takes a single argument, cmd , but it’s possible for type families to have several arguments and you’ll see some examples of that later on in this chapter. The kind signature, :: Type , specifies what the kind of the returned value should be. In this case, the return kind should be a normal type. Let’s write an instance of ShellCommand so that we can see how to use our type family, and get a chance to try using it in ghci . We’ll start by writing an instance for ListDirectory :

​  ​ instance ​ ​ ShellCommand ​ ​ ListDirectory ​ ​ where ​
​  ​ type ​ ​ ShellOutput ​ ​ ListDirectory ​ = [​ FilePath ​]
​  runCmd (​ ListDirectory ​ dir) run =
​  lines <$> run ​ "ls" ​ [​ "-1" ​, dir]

This tells the compiler that the ShellOutput type family, when when called with the type ListDirectory , returns a type of the value [FilePath] . If we load our module into ghci you can see that the kind of ShellOutput looks like a function from a Type to a Type :

​  ​ λ ​ :kind! ​ ShellOutput ​
​  ​ ShellOutput ​ :: ​ Type ​ -> ​ Type ​
​  = ​ ShellOutput ​

When we apply a Type , in thise case ListDirectory , we get back a type, [FilePath] . We can validate that in ghci too:

​  ​ λ ​ :kind! ​ ListDirectory ​
​  ​ ListDirectory ​ :: ​ Type ​
​  = ​ ListDirectory ​
​  
​  ​ λ ​ :kind! ​ ShellOutput ​ ​ ListDirectory ​
​  ​ ShellOutput ​ ​ ListDirectory ​ :: ​ Type ​
​  = [[​ Char ​]]

Remember that FilePath is an alias for String , which is itself an alias for [Char] , so you can see that ShellOutput ListDirectory is returning exactly what we told it to return.

You can see how we can call a type family in the definition of runCmd , where we’re using the type family to find the return type of runCmd :

​  runCmd ::
​  ​ Monad ​ m =>
​  cmd ->
​  (​ String ​ -> [​ String ​] -> m ​ String ​) ->
​  m (​ ShellOutput ​ cmd)

In this type annotation, cmd is a type variable, and we’re going to call ShellOutput with whatever value we happen to have in that variable. This lets us get the proper output type for any input type we call runCmd with. Let’s look at another example and see how we can write an instance for Grep using type families:

​  ​ instance ​ ​ ShellCommand ​ ​ Grep ​ ​ where ​
​  ​ type ​ ​ ShellOutput ​ ​ Grep ​ = [​ GrepMatch ​]
​  runCmd (​ Grep ​ match grepFiles) run =
​  parseGrepResponse . fixResponses . lines <$> run ​ "grep" ​ grepArgs
​  ​ where ​
​  grepArgs = ​ "-n" ​ : match : grepFiles
​  fixResponses :: [​ String ​] -> [​ String ​]
​  fixResponses responseLines =
​  ​ case ​ grepFiles ​ of ​
​  [fname] ->
​  (​ \ ​l -> fname <> ​ ":" ​ <> l) <$> responseLines
​  ​ _ ​ ->
​  responseLines

Just like with ListDirectory , we can define an instance for Grep with minimal changes to our code. Instead of a second parameter telling us that the result of a Grep should be a list of matches, we’re using a type family. As you would expect, we can load this up into ghci and see that we get the correct output from ShellOutput when called with Grep instead of ListDirectory :

​  ​ λ ​ :kind! ​ ShellOutput ​ ​ Grep ​
​  ​ ShellOutput ​ ​ Grep ​ :: ​ Type ​
​  = [​ GrepMatch ​]

Most developers these days prefer the syntax of type families over functional dependencies, but the two instances we’ve looked at so far haven’t shown much clear benefit to type families other than a bit of a nicer syntax. We can see a more obvious benefit when we define Pipe . By eliminating the second parameter to our type classes, composing them becomes much easier. With type families, we can redefine Pipe to need only two type parameters, one for each command on either end of the pipe:

​  ​ -- data Pipe a r b r' = Pipe a (r -> b) ​
​  ​ data ​ ​ Pipe ​ a b = ​ Pipe ​ a (​ ShellOutput ​ a -> b)

This new definition is more readable thanks to being able to remove two of our type parameters. It also carries a much more precise definition. Our old definition of Pipe didn’t enforce any particular relationship between all of its parameters. We might have known that r was supposed to be the output type of a and that r’ was supposed to be the output type of b , but there was nothing that required that to be the case. Using type families, we can be more explicit that the output type of the command a must be used to generate the command b .

The definition of ShellCommand for Pipe is also a little bit simpler thanks to the removed parameters:

​  ​ instance ​ (​ ShellCommand ​ a, ​ ShellCommand ​ b) =>
​  ​ ShellCommand ​ (​ Pipe ​ a b)
​  ​ where ​
​  ​ type ​ ​ ShellOutput ​ (​ Pipe ​ a b) = ​ ShellOutput ​ b
​  runCmd (​ Pipe ​ a mkB) run = ​ do ​
​  result <- runCmd a run
​  runCmd (mkB result) run

This example also highlights another important property of working with type families. The definition of ShellOutput (Pipe a b) refers to ShellOutput b . The ability to recursively solve for type families is what lets us write more complex computations at the type level than we could do before.

We still have one more opportunity to benefit from refactoring our code to use type families: we’re now able to define grepFilesInDirectory without needing to refer to the output types of either ListDirectory or Grep :

​  grepFilesInDirectory ::
​  ​ String ​ ->
​  ​ FilePath ​ ->
​  ​ Pipe ​ ​ ListDirectory ​ ​ Grep ​
​  grepFilesInDirectory match dir =
​  ​ Pipe ​ (​ ListDirectory ​ dir) $
​  ​ Grep ​ match . map (​ \ ​fname -> dir <> ​ "/" ​ <> fname)

Thanks to our new definition of Pipe , we’re able to join commands without having to explicitly refer to the output type, meaning that our users will be free to compose commands with less risk of breaking changes in the future. Unfortunately, even though we’re not explicitly naming the output type of ListDirectory we’re still relying on the implementation detail that it’s defined as [FilePath] . We’re able to do this because type families work similarly to type aliases. Any time we use ShellOutput ListDirectory it’s essentially a synonym for [FilePath] . Like with type aliases, this can have the down side that it may allow us to accidentally write code that depends on what should have been an implementation detail.

Associated Data Families

One way to avoid this problem is to use data families . A data family works like a type family, except that every data family instance defines a brand new type, rather than creating an alias for some existing type. Data families otherwise work like type families, except we use the data keyword instead of type . Let’s take one more pass at refactoring our shell library to use data families instead of type families. We’ll start by refactoring our type class definition:

​  ​ class ​ ​ ShellCommand ​ cmd ​ where ​
​  ​ data ​ ​ ShellOutput ​ cmd :: ​ Type ​
​  runCmd ::
​  ​ Monad ​ m =>
​  cmd ->
​  (​ String ​ -> [​ String ​] -> m ​ String ​) ->
​  m (​ ShellOutput ​ cmd)

You’ll notice that the only change to the definition of our type class is that we’re now using the keyword data instead of type . The changes to our instances will be a little bit more invasive, but not much. Let’s look at our ListDirectory instance next.

In this example, rather than directly translating our earlier type family, we’ll revisit what we return. One of the requirements we ran into was that we needed a way to add the parent directory to the name of the files in the directory listing. We can make that easier for ourselves by keeping the path to the directory alongside the directory listing. We can do that by defining a new record with our data family:

​  ​ instance ​ ​ ShellCommand ​ ​ ListDirectory ​ ​ where ​
​  ​ data ​ ​ ShellOutput ​ ​ ListDirectory ​ =
​  ​ DirectoryListing ​ { containingDirectory :: ​ FilePath ​
​  , filenamesInListing :: [​ FilePath ​]
​  } ​ deriving ​ (​ Show ​, ​ Eq ​)
​  runCmd (​ ListDirectory ​ dir) run =
​  ​ DirectoryListing ​ dir . lines <$> run ​ "ls" ​ [​ "-1" ​, dir]

As you can see, creating a new data family instance follows the same pattern that you used to create type family instances, but now we’re defining a brand new constructor called DirectoryListing and adding fields to it. The constructor we’re creating works just like any other constructor. You can see in this example that we’re deriving Show and Eq instances.

Before we move on to writing an instance for Grep using data families, let’s take advantage of this extra information we’re now storing to write a utility function to handle getting a list of files in a directory listing including the name of their parent directory.

​  directoryListingWithParent :: ​ ShellOutput ​ ​ ListDirectory ​ -> [​ FilePath ​]
​  directoryListingWithParent ​ DirectoryListing ​{..} =
​  map fixPath filenamesInListing
​  ​ where ​
​  fixPath fname =
​  containingDirectory <> ​ "/" ​ <> fname

You’ll notice in this example that we’re referring to the type of our record by the data family name, ShellOutput ListDirectory . Although the constructor and record field selectors are all visible like normal, our new record’s type is only accessible by applying our data family. Let’s take a quick look at ghci to get a feel for the types we have in scope so far:

​  ​ λ ​ :t ​ DirectoryListing ​
​  ​ DirectoryListing ​
​  :: ​ FilePath ​ -> [​ FilePath ​] -> ​ ShellOutput ​ ​ ListDirectory ​
​  ​ λ ​ :kind ​ ShellOutput ​ ​ ListDirectory ​
​  ​ ShellOutput ​ ​ ListDirectory ​ :: ​ Type ​
​  ​ λ ​ :t containingDirectory
​  containingDirectory :: ​ ShellOutput ​ ​ ListDirectory ​ -> ​ FilePath ​
​  ​ λ ​ :t filenamesInListing
​  filenamesInListing :: ​ ShellOutput ​ ​ ListDirectory ​ -> [​ FilePath ​]

In addition to defining brand new data types, we can also use newtype with data families to get the extra type safety benefits of a data family without any additional runtime overhead. Let’s create an instance of ShellCommand for Grep using a newtype wrapper instead of a brand new record type:

​  ​ instance ​ ​ ShellCommand ​ ​ Grep ​ ​ where ​
​  ​ newtype ​ ​ ShellOutput ​ ​ Grep ​ =
​  ​ ListOfGrepMatches ​ { getListOfGrepMatches :: [​ GrepMatch ​] }
​  
​  runCmd (​ Grep ​ match grepFiles) run =
​  ​ ListOfGrepMatches ​ . parseGrepResponse . fixResponses . lines <$>
​  run ​ "grep" ​ grepArgs
​  ​ where ​
​  grepArgs = ​ "-n" ​ : match : grepFiles
​  fixResponses :: [​ String ​] -> [​ String ​]
​  fixResponses responseLines =
​  ​ case ​ grepFiles ​ of ​
​  [fname] -> (​ \ ​l -> fname <> ​ ":" ​ <> l) <$> responseLines
​  ​ _ ​ -> responseLines

In this example, you can see when we want to use a newtype with a data family, we replace the data keyword with newtype . The instance of the data family is defined like any other newtype , and the constructor and our field selector are available just like they were when we defined our DirectoryListing record:

​  ​ λ ​ :t ​ ListOfGrepMatches ​
​  ​ ListOfGrepMatches ​ :: [​ GrepMatch ​] -> ​ ShellOutput ​ ​ Grep ​
​  
​  ​ λ ​ :t getListOfGrepMatches
​  getListOfGrepMatches :: ​ ShellOutput ​ ​ Grep ​ -> [​ GrepMatch ​]

As you can imagine, refactoring Pipe follows the same pattern that we’ve used for ListDirectory and Grep . If you’d like, you can jump ahead to the first exercise at the end of this chapter and complete refactoring this module to use data families.

Open Data and Type Families

After learning about associated data and type families, you might find yourself in a situation where you want to create a new type class just for the sake of having a data or type family. For example, imagine that you wanted to write some code that would let you generate type level string representations of some types. We can do that with associated types, but it ends up being pretty verbose:

​  ​ {-# LANGUAGE FlexibleInstances #-} ​
​  ​ {-# LANGUAGE TypeOperators #-} ​
​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE DataKinds #-} ​
​  ​ {-# LANGUAGE UndecidableInstances #-} ​
​  
​  ​ module ​ ​ EffectiveHaskell.Chapter15.OpenDataFamiliesDemo ​ ​ where ​
​  ​ import ​ ​ GHC.TypeLits ​
​  
​  ​ class ​ ​ HasNamedType ​ t ​ where ​
​  ​ type ​ ​ NamedType ​ t :: ​ Symbol ​
​  
​  ​ instance ​ ​ HasNamedType ​ ​ Int ​ ​ where ​
​  ​ type ​ ​ NamedType ​ ​ Int ​ = ​ "Int" ​
​  
​  ​ instance ​ ​ HasNamedType ​ ​ Char ​ ​ where ​
​  ​ type ​ ​ NamedType ​ ​ Char ​ = ​ "Char" ​
​  
​  ​ instance ​ ​ HasNamedType ​ ​ String ​ ​ where ​
​  ​ type ​ ​ NamedType ​ ​ String ​ = ​ "String" ​
​  
​  ​ instance ​ (​ HasNamedType ​ a, ​ HasNamedType ​ b) =>
​  ​ HasNamedType ​ (a -> b) ​ where ​
​  ​ type ​ ​ NamedType ​ (a -> b) =
​  ​ NamedType ​ a `​ AppendSymbol ​` ​ " -> " ​ `​ AppendSymbol ​` ​ NamedType ​ b

Open type families give us the same functionality without the need to explicitly define a type class. We call them open type families because, like type classes and associated type families, they are open to extension . In other words, we, or the user, can always add more instances later on without having to change the definition of the open type family. We can define an open type family at the top level of our module with the type family keywords, and create instances of the family with type instance . Let’s take a look at an open type family based version of NamedType :

​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE DataKinds #-} ​
​  ​ {-# LANGUAGE UndecidableInstances #-} ​
​  ​ {-# LANGUAGE TypeOperators #-} ​
​  
​  ​ module ​ ​ OpenDataFamilyDemo ​ ​ where ​
​  ​ import ​ ​ GHC.TypeLits ​
​  ​ import ​ ​ Data.Kind ​
​  
​  ​ type ​ family ​ NamedType ​ (a :: ​ Type ​) :: ​ Symbol ​
​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ Int ​ = ​ "Int" ​
​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ Char ​ = ​ "Char" ​
​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ String ​ = ​ "String" ​
​  ​ type ​ ​ instance ​ ​ NamedType ​ (a -> b) =
​  ​ NamedType ​ a `​ AppendSymbol ​` ​ " -> " ​ `​ AppendSymbol ​` ​ NamedType ​ b

In this example, you can see the open type family looks similar to the associated type family implementation, but it does away with some of the extra syntax we needed for defining the HasNamedType class. In fact, you can really think of associated type families as a special case of a more general open type family, where the type family has to be defined for every instance of a particular type class. This requirement lets us use the type family in the types of the functions defined inside of the class. If you don’t need to use the type family as part of the type of any functions in the class, then an open type family is essentially the same as an associated type family. We’ve also added a kind signature to the parameter of NamedType . In theory, we could have omitted the kind signature here, but adding kind signatures can help make our type level code safer and easier to read. Of course, we could have also added kind signatures to the parameters of our associated type family, but it’s more common to see the kind signatures omitted for the parameters of associated type familes since it will often be included in the definition of the type class.

Let’s open up ghci and try running a few commands to experiment with our new NamedType family. If we call our type family for any of the types we’ve defined instances for, we get back the string we’d expect:

​  ​ λ ​ :kind! ​ NamedType ​ ​ Int ​
​  ​ NamedType ​ ​ Int ​ :: ​ Symbol ​
​  = ​ "Int" ​
​  
​  ​ λ ​ :kind! ​ NamedType ​ ​ String ​
​  ​ NamedType ​ ​ String ​ :: ​ Symbol ​
​  = ​ "String" ​
​  
​  ​ λ ​ :kind! ​ NamedType ​ (​ String ​ -> ​ Int ​)
​  ​ NamedType ​ (​ String ​ -> ​ Int ​) :: ​ Symbol ​
​  = ​ "String -> Int" ​

We can even call our type family with a function that takes more than one argument, since currying will turn it into a single argument function for us:

​  ​ λ ​ :kind! ​ NamedType ​ (​ String ​ -> ​ Char ​ -> ​ Int ​ -> ​ Char ​)
​  ​ NamedType ​ (​ String ​ -> ​ Char ​ -> ​ Int ​ -> ​ Char ​) :: ​ Symbol ​
​  = ​ "String -> String -> Int -> Char" ​

If we try to call our type family with a type that we haven’t defined an instance for, you might expect that we’ll get an error. Instead, something unexpcted happens. The command will succeed, but the result will be an unevaluated type family expression:

​  ​ λ ​ :kind! ​ NamedType ​ (​ Bool ​ -> ​ Bool ​)
​  ​ NamedType ​ (​ Bool ​ -> ​ Bool ​) :: ​ Symbol ​
​  = ​ AppendSymbol ​
​  (​ AppendSymbol ​ (​ NamedType ​ ​ Bool ​) ​ " -> " ​) (​ NamedType ​ ​ Bool ​)

The problem here is that :kind! is telling ghci to do its best to run type checking and reduce our type level expression, but it’s not able to do so far enough to actually know that we have an error. Instead, it throws up its hands and gives us back the unevaluated expression. This can end up being a particular problem when you are using :kind! to type check your code, but not looking closely at the output. Since the result isn’t an error, it’s easy to look past the fact that the result is partially unevaluated and realize that this means you may have a type family that isn’t actually defined.

One way that we can get a more through test of our type level code is to use it to generate an actual term level value, but our type family is generating a purely type level string. How can we turn that into something at the term level that we can run, and use to test our type family instances?

We’ll start by using one of the useful functions that is provided to use in GHC.TypeLits , the symbolVal function. It has the type:

​  symbolVal :: ​ KnownSymbol ​ n => proxy n -> ​ String ​

The KnownSymbol constraint is a type class constraint that’s defined for all Symbol types. This means we know that n must be some kind of type level string. Knowing we have a type level string is good, since we want to get a term level string that matches the type level string, but it presents a problem. We need to pass something into symbolVal so that it can keep track of the type information it needs to return a string value, but we can’t actually create any term level values with a symbol type. This is a common problem when we’re dealing with type level code, but there’s a straightforward solution: phantom types. We don’t need a value whose type is a symbol, we just need a value whose type carries the symbol information along with it. We typically call values like this proxies .

The Data.Proxy module from base gives us a useful default definition for a proxy that looks like this:

​  ​ data ​ ​ Proxy ​ a = ​ Proxy ​

In other words, a Proxy is a type that only has a single inhabitant, Proxy , but it can carry around any type information that we want. If you’re reading carefully though, you’ll notice that symbolVal ’s proxy is a type parameter, with a lowercase p . Since we’ll never use the value of a proxy type, there’s no reason to restrict it to being an actual Proxy , even if that’s what you’ll use as a proxy value most of the time.

You can use a proxy value with either a visible type application or a type annotation. Let’s look at a couple of examples in ghci :

​  ​ λ ​ symbolVal (​ Proxy ​ :: ​ Proxy ​ ​ "Hello" ​)
​  ​ "Hello" ​
​  
​  ​ λ ​ symbolVal $ ​ Proxy ​ @​ "World" ​
​  ​ "World" ​

As you can see, Proxy let’s us carry around the type information for a symbol and pass it into symbolVal so that we can get back a runtime string representation of the type literal string that we passed in. If we use the ScopedTypeVariables extension, we can also create a proxy value to carry around the information about a polymorphic type. Let’s put this all together and write a new function, showTypeName that will take a type with a NamedType instance and generate a term level string representation. We’ll need to start by enabling the FlexibleContexts extension.

FlexibleContexts

| images/aside-icons/info.png | The FlexibleContexts extension has been available since GHC 6.8.1. It’s enabled by default in GHC2021 but if you’re using Haskell2010 you’ll need to enable it manually. This is generally a safe extension that shouldn’t cause problems with any existing code. |

​  ​ {-# LANGUAGE AllowAmbiguousTypes #-} ​
​  ​ {-# LANGUAGE ScopedTypeVariables #-} ​
​  ​ {-# LANGUAGE FlexibleContexts #-} ​
​  ​ {-# LANGUAGE TypeApplications #-} ​
​  
​  showTypeName :: forall t. (​ KnownSymbol ​ (​ NamedType ​ t)) => ​ String ​
​  showTypeName = symbolVal $ ​ Proxy ​ @(​ NamedType ​ t)

In this example, our function’s type says the return type of NamedType must be a known symbol. With FlexibleContexts , we’re allowed to call the NamedType family directly inside of the KnownSymbol constraint. Without this extension, we can only have constraints on type names.

Whatever that type happens to be, we’ll create a proxy value that holds that type information, and passes it into symbolVal so that we can get a runtime string. Let’s try it out in ghci :

​  ​ λ ​ showTypeName @​ Int ​
​  ​ "Int" ​
​  
​  ​ λ ​ showTypeName @​ Char ​
​  ​ "Char" ​
​  
​  ​ λ ​ showTypeName @(​ Int ​ -> ​ Int ​ -> ​ String ​)
​  ​ "Int -> Int -> String" ​

In these examples, we’re sticking to types that have NamedType instances, and as we’d expect we’re getting back term level strings. We can use these strings like any other string:

​  ​ λ ​ typeName :: ​ String ​ = showTypeName @(​ String ​ -> ​ Int ​)
​  
​  ​ λ ​ putStrLn $
​  ​ "The type '" ​ <> typeName <> ​ "' is " ​ <> show (length typeName) <> ​ " chars" ​
​  ​ The ​ ​ type ​ ​ 'S ​​ t ​ring -> ​ Int' ​ is 13 chars

Unlike our examples using :kind! , if we try to pass a type that doesn’t have a NamedType instance to showTypeName we’ll get an error:

​  λ showTypeName @Bool
​  <interactive>:907:1-12: error:
​  • No instance for (KnownSymbol (NamedType Bool))
​  arising from a use of ‘showTypeName’
​  • In the expression: showTypeName @Bool
​  In an equation for ‘it’: it = showTypeName @Bool

Why does this function successfully give us an error when looking at the kind didn’t? It’s because in this function we’re forced to actually pick a particular instance of the KnownSymbol type class so that we get a string out of it, and at that point we’re forced to deal with the fact that there’s no instance defined for NamedType Bool . As you’ll see later in this chapter, type classes are an important part of writing type level code, because they give us a way to map the computed types back to term level values.

Now that we have a way to more easily test our type family, and we can get useful errors out of it, let’s make a few quality of life improvements by adding a some additional compound types. Let’s start by adding an instance for tuples:

​  ​ type ​ ​ instance ​ ​ NamedType ​ (a,b) =
​  ​ "(" ​ `​ AppendSymbol ​` ​ NamedType ​ a `​ AppendSymbol ​` ​ "," ​
​  `​ AppendSymbol ​` ​ NamedType ​ b `​ AppendSymbol ​` ​ ")" ​

This is starting to get a bit unreadable thanks to the repeated use of infix AppendSymbol calls. Thankfully, we can create type operator aliases for type families the same way we could for lifted data types. Let’s try to add a new operator and then refactor our NamedType instance to use it:

​  ​ type ​ (:++:) = ​ AppendSymbol ​
​  
​  ​ type ​ ​ instance ​ ​ NamedType ​ (a,b) =
​  ​ "(" ​ :++: ​ NamedType ​ a :++: ​ "," ​ :++: ​ NamedType ​ b :++: ​ ")" ​

Unfortunately, when we try to compile this refactored example, we get a new error:

​  src/OpenDataFamilyDemo.hs:15:1-26: error: ...
​  • The type family ‘AppendSymbol’ should have 2 arguments,
​  but has been given none
​  • In the type synonym declaration for ‘:++:’
​  |
​  Compilation failed.

This error illustrates one of the biggest limitations that we have with type families compared to term level functions. We’re not allowed to use partially applied type families. Although we’re free to reference constructors without passing in all of their arguments, like we did when we created a type operator for Cons earlier, a type family must always have all of its arguments applied. This restriction can be particularly troublesome if you want to write higher order functions like map or fold at the type level. You’ll learn how to handle this situation later on in the chapter. Thankfully, in this case we can work around that restriction without too much trouble by adding type parameters to both sides of our operator:

​  ​ type ​ (:++:) a b = ​ AppendSymbol ​ a b
​  
​  ​ type ​ ​ instance ​ ​ NamedType ​ (a,b) =
​  ​ "(" ​ :++: ​ NamedType ​ a :++: ​ "," ​ :++: ​ NamedType ​ b :++: ​ ")" ​

With our new type family instance in place, we can now get nicely formatted versions of types that include tuples:

​  ​ λ ​ showTypeName @(​ Char ​ -> ​ String ​, ​ String ​ -> ​ Int ​)
​  ​ "(Char -> String,String -> Int)" ​
​  
​  ​ λ ​ showTypeName @(​ String ​ -> (​ Int ​, ​ Char ​))
​  ​ "String -> (Int,Char)" ​

Now that we’ve covered tuples, let’s try to add an instance that will let us format list types. We’ll follow the same pattern we used for tuples:

​  ​ type ​ ​ instance ​ ​ NamedType ​ [a] = ​ "[" ​ :++: ​ NamedType ​ a :++: ​ "]" ​

Once again, if we compile this we’re faced with an error. This time the compiler is letting us know that we have conflicting instances:

​  src/OpenDataFamilyDemo.hs:19:15-23: error: …
​  Conflicting family instance declarations:
​  NamedType String = "String"
​  -- Defined at /examples/OpenDataFamilyDemo.hs:19:15
​  NamedType [a] = ("[" :++: NamedType a) :++: "]"
​  -- Defined at /examples/OpenDataFamilyDemo.hs:23:15
​  |
​  Compilation failed.

The problem we’re running into now is String is an alias for the type [Char] , but our new instance defined for [a] will match any list type, including [Char] . Open type families are very particular about overapping instances. We’re only allowed to have to instances that overlap if all of the overlapping instances would return exactly the same value in the overlapping cases. We can see that this is the case if we hardcode both our String and [a] instances to always return "" :

​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ String ​ = ​ "" ​
​  ​ type ​ ​ instance ​ ​ NamedType ​ [a] = ​ "" ​

In this case, since the overlapping instances always return the same type the compiler accepts the overlap. Relying on this exception can be tricky though, since the types that each of the overlapping instances return needs to be structurally equal. For example, imagine that we hadn’t yet defined an instance for String , but we had a list instance defined like this:

​  ​ type ​ ​ instance ​ ​ NamedType ​ [a] = ​ "[" ​ :++: ​ NamedType ​ a :++: ​ "]" ​

Now, let’s call NamedType String and see what we get back:

​  ​ λ ​ :kind! ​ NamedType ​ ​ String ​
​  ​ NamedType ​ ​ String ​ :: ​ Symbol ​
​  = ​ "[Char]" ​

Next, let’s add our String instance back, but this time we’ll hard-code the return type of "[Char]" . That seems like it should work, since it’s exactly what we got when we evaluated the type family in ghci :

​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ String ​ = ​ "[Char]" ​

The compiler seems to have a different idea of equality than we do. If we try to compile this we’ll still get an error:

​  src/OpenDataFamilyDemo.hs:20:15-23: error: …
​  Conflicting family instance declarations:
​  NamedType String = "[Char]"
​  -- Defined at /examples/OpenDataFamilyDemo.hs:20:15
​  NamedType [a] = ("[" :++: NamedType a) :++: "]"
​  -- Defined at /examples/OpenDataFamilyDemo.hs:24:15
​  |
​  Compilation failed.

Even though it seems like these two expressions ought to be the same, the compiler still won’t accept this, since our literal symbol is structurally different from the computed symbol we’re generating in our list instance. Let’s give this another try. This time we’ll be a bit more explicit about replicating the same structure by using (:++:) to combine the different parts of our symbol:

​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ String ​ = ​ "[" ​ :++: ​ "Char" ​ :++: ​ "]" ​

Unfortunately that still doesn’t seem to be sufficient. If you try to compile this version you’ll see that you’re getting a similar error: the compiler still doesn’t consider these two types equal. We have one more option. Let’s replace the symbol literal "Char" with a call to NamedType :

​  ​ type ​ ​ instance ​ ​ NamedType ​ ​ String ​ = ​ "[" ​ :++: ​ NamedType ​ ​ Char ​ :++: ​ "]" ​

If you try to compile this version of the code you’ll see that we’ve finally found an instance that can successfully overlap. In order to do that, we needed to make sure that we were returning exactly the same type that we would have returned in our list instance, without any additional normalization.

Closed Data and Type Families

Open and associated type families are certainly useful, but the fact that they can be arbitrarily extended by users of our library also puts some limitations on the computations that we can reasonably do with them. Closed data and type families give us another way to write type level functions that give up extensibility, and in exchange there are different sorts of computations that we can build with them. This is thanks to the fact that we’ll know every instance of a closed type family that will exist at the time it’s defined. That lets us handle our cases exhaustively. In this section, we’ll look at two different examples of how we can used closed type families to write type level computations. First, we’ll look at how we can use type families to implement some basic arithmetic on peano numbers to get a feel for the syntax and basics of using type familes. Next, we’ll work through some examples of working with type level lists using open and closed type families together to give us even more flexiblity.

You first learned about peano numbers much earlier in this book, when you first learned about creating your own types . Although GHC already gives us convenient access to type level literals, peano numbers are still useful because they are a great example of how to work with closed type families. Let’s revisit our peano numbers, but this time we’ll use them at the type level.

The first thing we’ll want to do is create a new module and add in our definition of peano numbers:

​  ​ {-# LANGUAGE UndecidableInstances #-} ​
​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE DataKinds #-} ​
​  ​ {-# LANGUAGE TypeOperators #-} ​
​  
​  ​ module ​ ​ ClosedTypeFamilyDemo ​ ​ where ​
​  ​ import ​ ​ GHC.TypeLits ​
​  
​  ​ data ​ ​ Peano ​ = ​ Zero ​ | ​ Succ ​ ​ Peano ​

The first problem that we’ll run into working with peano numbers, whether it’s at the type or term level, is that it’s annoying to type out the numbers when we have to manually nest the constructors. Since we know that GHC already provides us with a nice way of writing type level Natural values using numeric literals, let’s create a new type family to convert a Natural to a Peano .

The algorithm we want to implement for this is straightforward:

  • If the Natural number is 0 , then return Zero .
  • If it’s anything larger than zero, return the successor of converting the next smallest natural number to a Peano .

If we try to implement this using an open type family though, we’ll run into a problem: the most natural way of expressing this algorithm runs into the dreaded overlapping instances problem. Let’s try it and see for ourselves:

​  ​ type ​ family ​ ToPeano ​ (n :: ​ Natural ​) :: ​ Peano ​
​  ​ type ​ ​ instance ​ ​ ToPeano ​ 0 = ​ Zero ​
​  ​ type ​ ​ instance ​ ​ ToPeano ​ a = ​ Succ ​ (​ ToPeano ​ (a - 1))

If you try to compile this you’ll quickly see the problem: a can match anything , including 0 , so it will overlap the instance that should be acting as the base case of our recursion.

Thankfully, we have another option. We can write ToPeano using a closed type family. Overlap is allowed in closed type families. Like guard clauses and case expressions, overlap in a closed type family is resolved top-to-bottom. Let’s rewrite ToPeano as a closed type family and see how it works:

​  ​ type ​ family ​ ToPeano ​ (n :: ​ Natural ​) :: ​ Peano ​ ​ where ​
​  ​ ToPeano ​ 0 = ​ Zero ​
​  ​ ToPeano ​ a = ​ Succ ​ (​ ToPeano ​ (a - 1))

The first thing to notice is that the closed type family version of our code works as expected. If we load it up into ghci we can successfully convert naturals into peano numbers:

​  ​ λ ​ :kind! ​ ToPeano ​ 3
​  ​ ToPeano ​ 3 :: ​ Peano ​
​  = ​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc ​ 'Z ​​ e ​ro))
​  
​  ​ λ ​ :kind! ​ ToPeano ​ 5
​  ​ ToPeano ​ 5 :: ​ Peano ​
​  = ​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc ​ 'Z ​​ e ​ro))))

You’ll notice that the syntax for creating a closed type family is similar to that of an open type family, but now we include all of the instances inside of a where clause rather than creating instances using type instance . Before we move on, let’s write a FromPeano instance as well, so that we can easily convert back and forth between Natural and Peano representations of numbers:

​  ​ type ​ family ​ FromPeano ​ (a :: ​ Peano ​) :: ​ Natural ​ ​ where ​
​  ​ FromPeano ​ ​ Zero ​ = 0
​  ​ FromPeano ​ (​ Succ ​ a) = 1 + ​ FromPeano ​ a

Now we can round trip between Peano and Natural representations of numbers:

​  ​ λ ​ :kind! ​ FromPeano ​ (​ ToPeano ​ 10)
​  ​ FromPeano ​ (​ ToPeano ​ 10) :: ​ Natural ​
​  = 10
​  
​  ​ λ ​ :kind! ​ ToPeano ​ (​ FromPeano ​ (​ Succ ​ (​ Succ ​ (​ Succ ​ ​ Zero ​))))
​  ​ ToPeano ​ (​ FromPeano ​ (​ Succ ​ (​ Succ ​ (​ Succ ​ ​ Zero ​)))) :: ​ Peano ​
​  = ​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc ​ 'Z ​​ e ​ro))

Being able to convert back and forth between different representations of a number will be useful as we’re working through some more examples, but it’s not particularly interesting on its own. Let’s make our Peano numbers more useful by adding some basic arithmetic operations for them. We’ll start with addition and multiplication. Unlike our earlier type family examples, these will need to take two parameters. Luckily, adding extra parameters to a type family is straightforward:

​  ​ type ​ family ​ Add ​ (a :: ​ Peano ​) (b :: ​ Peano ​) :: ​ Peano ​ ​ where ​
​  ​ Add ​ a ​ Zero ​ = a
​  ​ Add ​ a (​ Succ ​ b) = ​ Add ​ (​ Succ ​ a) b
​  
​  ​ type ​ family ​ Multiply ​ (a :: ​ Peano ​) (b :: ​ Peano ​) :: ​ Peano ​ ​ where ​
​  ​ Multiply ​ a ​ Zero ​ = ​ Zero ​
​  ​ Multiply ​ a (​ Succ ​ ​ Zero ​) = a
​  ​ Multiply ​ a (​ Succ ​ b) = ​ Add ​ a (​ Multiply ​ a b)

One thing to notice about all the examples we’ve looked at so far is we’re defining total functions. We can add or multiply any two peano numbers and get a number back out. Not all operations we might want to support are this flexible though. If we want to support subtraction, we’ll quickly run into a problem: we can’t represent negative numbers with Peano , but there’s nothing stopping our users from trying to subtract a bigger number from a smaller one.

If we try to naively define Subtract it will work for cases where the numbers are subtractable, but if a user tries to do an invalid operation, we’ll run into the same situation we encountered with NamedType —we’ll get an unnormalized type instead of a useful error. Let’s try it out and see:

​  ​ type ​ family ​ Subtract ​ (a :: ​ Peano ​) (b :: ​ Peano ​) :: ​ Peano ​ ​ where ​
​  ​ Subtract ​ a ​ Zero ​ = a
​  ​ Subtract ​ (​ Succ ​ a) (​ Succ ​ b) = ​ Subtract ​ a b

If we load this into ghci we’ll get reasonable values for valid operations:

​  ​ λ ​ :kind! ​ FromPeano ​ (​ Subtract ​ (​ ToPeano ​ 10) (​ ToPeano ​ 2))
​  ​ FromPeano ​ (​ Subtract ​ (​ ToPeano ​ 10) (​ ToPeano ​ 2)) :: ​ Natural ​
​  = 8

Now let’s try to subtract 10 from 2 and see what we get:

​  ​ FromPeano ​ (​ Subtract ​ (​ ToPeano ​ 2) (​ ToPeano ​ 10)) :: ​ Natural ​
​  = ​ FromPeano ​
​  (​ Subtract ​
​  ​ 'Z ​​ e ​ro
​  (​ 'S ​​ u ​cc
​  (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc (​ 'S ​​ u ​cc ​ 'Z ​​ e ​ro)))))))))

Just like when we were working with symbols, we have the option of trying to get a runtime value out of our invalid subtraction so that we can force an error. Let’s use the natValue function from GHC.TypeLits :

​  λ :type natVal
​  natVal :: KnownNat n => proxy n -> Integer
​  λ natVal $ Proxy @(FromPeano (Subtract (ToPeano 10) (ToPeano 2)))
​  8
​  λ natVal $ Proxy @(FromPeano (Subtract (ToPeano 2) (ToPeano 10)))
​  <interactive>:2228:1-6: error:
​  • No instance for
​  (KnownNat
​  (FromPeano
​  (Subtract
​  'Zero
​  ('Succ
​  ('Succ
​  ('Succ
​  ('Succ
​  ('Succ
​  ('Succ
​  ('Succ
​  ('Succ 'Zero)))))))))))
​  arising from a use of ‘natVal’
​  • In the first argument of ‘($)’, namely ‘natVal’
​  In the expression:
​  natVal $
​  Proxy @(FromPeano (Subtract (ToPeano 2) (ToPeano 10)))
​  In an equation for ‘it’:
​  it
​  = natVal $
​  Proxy @(FromPeano (Subtract (ToPeano 2) (ToPeano 10)))

Even though we can get a runtime error with natValue there are two problems. First, it would be preferable if we could get the type error at the type level, rather than requiring that we try to get a term level value. Second, and more notably, the error message that we’re getting here is unreadable and larger numbers result in even less readable and more deeply nested error messages. Type level programming can easily lead to cases where you can end up with impossibly complex error messages.

Thankfully, we can address both the problem of unreadable errors and the lack of errors when working at the type level in ghci with a single change: creating a user-defined type error. We can create a user-defined type error using TypeError and Text from GHC.TypeLits . Let’s add a type error to Subtract :

​  ​ type ​ family ​ Subtract ​ (a :: ​ Peano ​) (b :: ​ Peano ​) :: ​ Peano ​ ​ where ​
​  ​ Subtract ​ a ​ Zero ​ = a
​  ​ Subtract ​ ​ Zero ​ b =
​  ​ TypeError ​ (​ Text ​ ​ "Subtract: Cannot result in a negative number" ​)
​  ​ Subtract ​ (​ Succ ​ a) (​ Succ ​ b) = ​ Subtract ​ a b

In this example, TypeError is a type family that can be used to generate a compile time type error. We call it with an error message that we can generate with Text . Now if we try to evaluate an invalid subtraction in ghci we’ll see that the result would be a type error, and if we try to get a runtime value we’ll see that our error message is much easier to read:

​  λ :kind! Subtract (ToPeano 5) (ToPeano 10)
​  Subtract (ToPeano 5) (ToPeano 10) :: Peano
​  = (TypeError ...)
​  
​  λ natVal $ Proxy @(FromPeano (Subtract (ToPeano 5) (ToPeano 10)))
​  <interactive>:2271:1-6: error:
​  • Subtract: Cannot result in a negative number
​  • In the first argument of ‘($)’, namely ‘natVal’
​  In the expression:
​  natVal $ Proxy @(FromPeano (Subtract (ToPeano 5) (ToPeano 10)))
​  In an equation for ‘it’:
​  it
​  = natVal $
​  Proxy @(FromPeano (Subtract (ToPeano 5) (ToPeano 10)))

You can also get a bit more creative with your error messages to make them even more useful. For example, ShowType lets you print the value of a type in the error message. You can also combine error messages onto the same line with (:<>:) , or create multiple lines of error message output with (:$$:) . Let’s look at one more example of a more nicely formatted error message:

​  ​ type ​ family ​ Subtract ​ (a :: ​ Peano ​) (b :: ​ Peano ​) :: ​ Peano ​ ​ where ​
​  ​ Subtract ​ a ​ Zero ​ = a
​  ​ Subtract ​ ​ Zero ​ b = ​ TypeError ​ (
​  ​ Text ​ ​ "Subtract: Cannot result in a negative number" ​ :$$:
​  ​ Text ​ ​ "The result would be -" ​ :<>: ​ ShowType ​ (​ FromPeano ​ b))
​  ​ Subtract ​ (​ Succ ​ a) (​ Succ ​ b) = ​ Subtract ​ a b

This version of our error will not only explain that we can’t have a negative peano number, it will even tell the user what negative value they would have gotten if negative numbers were allowed:

​  λ natVal $ Proxy @(FromPeano (Subtract (ToPeano 5) (ToPeano 10)))
​  <interactive>:2274:1-6: error:
​  • Subtract: Cannot result in a negative number
​  The result would be -5
​  • In the first argument of ‘($)’, namely ‘natVal’
​  In the expression:
​  natVal $
​  Proxy @(FromPeano (Subtract (ToPeano 5) (ToPeano 10)))
​  In an equation for ‘it’:
​  it
​  = natVal $
​  Proxy @(FromPeano (Subtract (ToPeano 5) (ToPeano 10)))

User-defined type errors are common in closed type families. Since a closed type family should be exhaustive and supports overlap, it’s often straightforward to have a “catch-all” error case to give the user information about unsupported calls to the type family. You can also use type errors with open and associated type families, and as you’ll see later in this chapter, with type classes.

Now that you’ve learned the basics about type families using peano numbers, let’s move on to some more advanced examples of the sort of computations that you can do with type level families.

Type Level List Operations with Type Families

Earlier in this chapter, you learned about type level lists, but so far we’ve been limited to using them in fairly simple ways. None of the common functions you’ve come to expect for term level lists are defined for us at the type level, so we’ll need to write them ourselves if we want to get more use out of lists for type level computation. In this section, we’ll build a few list functions to help make working with lists easier at the type level.

As usual, let’s start by creating a new module and adding some language extensions:

​  ​ {-# LANGUAGE UndecidableInstances #-} ​
​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE TypeOperators #-} ​
​  ​ {-# LANGUAGE PolyKinds #-} ​
​  ​ {-# LANGUAGE DataKinds #-} ​
​  
​  ​ module ​ ​ TypeFamilyListFuncs ​ ​ where ​
​  ​ import ​ ​ GHC.TypeLits ​
​  ​ import ​ ​ Data.Kind ​

Now that we have the necessary boilerplate in place, let’s start by adding a new closed type family that will let us search to see if a particular value is inside of a type level list:

​  ​ type ​ family ​ Member ​ (needle :: a) (haystack :: [a]) :: ​ Bool ​ ​ where ​
​  ​ Member ​ a ​ '[ ​​ ] ​ = ​ False ​
​  ​ Member ​ a (a : as) = ​ True ​
​  ​ Member ​ a (b : as) = ​ Member ​ a as

If you look at this example closely, you’ll notice one of the big differences between pattern matching in type families compared to term level code like case expressions. Let’s look at the line in more detail:

​  ​ Member ​ a (a : as) = ​ True ​

In this line of code we’re testing to see if the element we’re searching for matches the head of the list, and we do it by using the same variable, a . In term level code this would fail and the compiler would warn us that we were trying to bind the same name to two different expressions, but at the type level using the same variable in a pattern means that the pattern will only match if the value of the variable is equal in both places.

Unfortunately, this feature also invites a bug that we wouldn’t have to worry about in the term level. Consider the very next line of our type family:

​  ​ Member ​ a (b : as) = ​ Member ​ a as

In this example, b is a distinct type variable, so a and b do not need to be equal, but the expression also does not prohibit them from being equal. In other words, our two type family instances will overlap in the case that the head of the list is the element we’re searching for. If we reverse the order of these two lines of code, the behavior would change and we would never report that we’d successfully found a match. With -Wall enabled you’ll get a warning about this, but otherwise it can be a confusing source of bugs.

Thankfully, we’ve done our overlap in the correct order, so we can load our code up into ghci and see it in action:

​  ​ λ ​ :kind! ​ Member ​ 1 ​ '[ ​​ ] ​
​  ​ Member ​ 1 ​ '[ ​​ ] ​ :: ​ Bool ​
​  = ​ 'F ​​ a ​lse
​  
​  ​ λ ​ :kind! ​ Member ​ 1 ​ '[ ​​ 1 ​,2,3]
​  ​ Member ​ 1 ​ '[ ​​ 1 ​,2,3] :: ​ Bool ​
​  = ​ 'T ​​ r ​ue
​  
​  ​ λ ​ :kind! ​ Member ​ 1 ​ '[ ​​ 2 ​,3,4]
​  ​ Member ​ 1 ​ '[ ​​ 2 ​,3,4] :: ​ Bool ​
​  = ​ 'F ​​ a ​lse

Knowing when a type level list contains a particular element is quite useful, and you’ll see some examples of how we can apply this later on in the chapter, but it’s a bit limited. It would be nice if we could find all of the elements that satisfied some particular predicate, like being even. Writing a function like this at the term level would be easy enough:

​  findElems :: (a -> ​ Bool ​) -> [a] -> [a]
​  findElems ​ _ ​ ​ [] ​ = ​ [] ​
​  findElems p (x:xs) =
​  ​ if ​ p x ​ then ​ x : findElems p xs ​ else ​ findElems p xs

At the type level, writing a function like this is challenging because we’re dealing with a higher order function, and that means we need a way to pass a type level function into a type family. As you learned earlier in this chapter, we can’t use partially applied type families, so we’ll need to use some new techniques to work around the limitation.

Let’s start by writing a version of FindElems that works the way we’d like it to work, imagining some features that we’d like to have along the way. Then we’ll try to either build the features we’ve imagined, or refactor FindElems until we get to some code that actually works.

​  ​ type ​ family ​ FindElems ​ (p :: a -> ​ Bool ​) (elems :: [a]) :: [a] ​ where ​
​  ​ FindElems ​ ​ _ ​ ​ '[ ​​ ] ​ = ​ '[ ​​ ] ​
​  ​ FindElems ​ p (a:as) =
​  ​ If ​ p a ​ Then ​ (a : ​ FindElems ​ p as) ​ Else ​ (​ FindElems ​ p as)

The imaginary implementation of FindElems in this example is relying on two major features that are missing from our knowledge so far. First, we’re assuming the user can pass in a type family that hasn’t been fully applied. Second, we’re trying to use an if expression, even though there’s nothing like that defined for us at the type level.

Before we tackle the harder problem of dealing with higher order type level functions, let’s address the lack of conditionals at the type level. The lack of conditional expressions at the type level might seem like a major oversight, but it turns out that it’s very easy for us to write our own as long as we’re willing to compromise on the precise syntax. Instead of using If , Then , and Else as individual keywords, we can write a type family that takes three parameters and will handle branching for us. We’ll call it IfThenElse :

​  ​ type ​ family ​ IfThenElse ​ (p :: ​ Bool ​) (t :: a) (f :: a) :: a ​ where ​
​  ​ IfThenElse ​ ​ True ​ t ​ _ ​ = t
​  ​ IfThenElse ​ ​ False ​ ​ _ ​ f = f

This type family will take a predicate value, and values for each branch. If the predicate is true, we return the true branch, and otherwise we will return the false branch. Let’s refactor FindElems to use this new type family:

​  ​ type ​ family ​ FindElems ​ (p :: a -> ​ Bool ​) (elems :: [a]) :: [a] ​ where ​
​  ​ FindElems ​ ​ _ ​ ​ '[ ​​ ] ​ = ​ '[ ​​ ] ​
​  ​ FindElems ​ p (a:as) =
​  ​ IfThenElse ​ (p a) (a : ​ FindElems ​ p as) (​ FindElems ​ p as)

Now that we’ve dealt with branching, we need to revisit the fact that FindElems needs to take a function. We can’t pass a type family in, because we’re not allowed to use type families that haven’t had all of their arguments applied, but type families aren’t the only way we can represent something like (a -> Bool) at the type level. Type constructors take arguments, and we are allowed to pass those into a type family without having applied all of their arguments. We need to figure out a way to represent a type level function as data.

Thankfully for us, there’s a well-established technique for removing higher order functions and replacing them with data. It’s called defunctionalization , and we can do it using things we’ve already learned about working with type families and data kinds.

The first step to defunctionalizing FindElems is to create a type constructor that will represent the computation we want to pass into FindElems . If we wanted to pass in a function that would select even numbers, we might start with something like this:

​  ​ data ​ ​ Even ​ (n :: ​ Natural ​)

In this example we’re creating a new type, Even . We don’t need to define any constructors, since we’ll only ever use this at the type level. You might have noticed the problem that we have here already, but if not, let’s take a look at the kind of Even in ghci :

​  ​ λ ​ :kind ​ Even ​
​  ​ Even ​ :: ​ Natural ​ -> ​ Type ​

Even has the kind Type , but we originally wanted something that will return a type of kind Bool . Using defunctionalization means we’re going to have to compromise on the exact kind of the value we pass into FindElems though. Any type that we create, once we’ve applied all of our arguments, will end up having the kind Type . That doesn’t mean we can’t capture the return type of the computation the data type represents though—we just need to add it as an extra parameter. Let’s do another round of refactoring:

​  ​ data ​ ​ Even ​ (n :: ​ Natural ​) (r :: ​ Bool ​)
​  ​ type ​ family
​  ​ FindElems ​ (p :: a -> ​ Bool ​ -> ​ Type ​) (elems :: [a]) :: [a]
​  ​ where ​
​  ​ FindElems ​ ​ _ ​ ​ '[ ​​ ] ​ = ​ '[ ​​ ] ​
​  ​ FindElems ​ p (a:as) =
​  ​ IfThenElse ​ (p a) (a : ​ FindElems ​ p as) (​ FindElems ​ p as)

Now if we look at the kind of Even in ghci we’ll see that it matches up exactly with what we want to pass into FindElems :

​  ​ λ ​> :kind ​ Even ​
​  ​ Even ​ :: ​ Natural ​ -> ​ Bool ​ -> ​ Type ​

Although our kinds line up, it’s a little bit awkward to read. There are a couple of small quality of life refactors we can make so that our code will be easier to read. First, we can replace (Bool -> Type) with a type alias that will abstract away the implementation detail that our defunctionalized types have to have the kind Type . Second, we can use a kind signature rather than named parameters when we define Even so that it matches up with the argument to FindElems . Let’s make one more refactoring pass:

​  ​ type ​ ​ ReturnValue ​ r = r -> ​ Type ​
​  ​ data ​ ​ Even ​ :: ​ Natural ​ -> ​ ReturnValue ​ ​ Bool ​
​  ​ type ​ family
​  ​ FindElems ​ (p :: a -> ​ ReturnValue ​ ​ Bool ​) (elems :: [a]) :: [a]
​  ​ where ​
​  ​ FindElems ​ ​ _ ​ ​ '[ ​​ ] ​ = ​ '[ ​​ ] ​
​  ​ FindElems ​ p (a:as) =
​  ​ IfThenElse ​ (p a) (a : ​ FindElems ​ p as) (​ FindElems ​ p as)

We’re getting closer to a working type family, but we’ve still got some work left to do. The most obvious problem we have right now is that we’ve created a new type that represents the function we want to pass in, but we haven’t actually defined any sort of computation that we can do with it. In other words, we’ve turned our function into a type so that we can pass it into the type family, but now we need to turn it back into a function.

So, we have an input value that is a type with the kind a -> ReturnValue Bool and we need to get out a type with the kind Bool . We need a function from a type to a type, which means that we need another type family . Let’s add a new type family called EvalEven that will perform the computation for the Even type that we’re passing in:

​  ​ {-# LANGUAGE UndecidableInstances #-} ​
​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE TypeOperators #-} ​
​  ​ {-# LANGUAGE PolyKinds #-} ​
​  ​ {-# LANGUAGE DataKinds #-} ​
​  
​  ​ module ​ ​ TypeFamilyListFuncs ​ ​ where ​
​  ​ import ​ ​ GHC.TypeLits ​
​  ​ import ​ ​ Data.Kind ​
​  
​  ​ type ​ family ​ IfThenElse ​ (p :: ​ Bool ​) (t :: a) (f :: a) :: a ​ where ​
​  ​ IfThenElse ​ ​ True ​ t ​ _ ​ = t
​  ​ IfThenElse ​ ​ False ​ ​ _ ​ f = f
​  
​  ​ type ​ ​ ReturnValue ​ r = r -> ​ Type ​
​  ​ data ​ ​ Even ​ :: ​ Natural ​ -> ​ ReturnValue ​ ​ Bool ​
​  
​  ​ type ​ family
​  ​ FindElems ​ (p :: a -> ​ ReturnValue ​ ​ Bool ​) (elems :: [a]) :: [a]
​  ​ where ​
​  ​ FindElems ​ ​ _ ​ ​ '[ ​​ ] ​ = ​ '[ ​​ ] ​
​  ​ FindElems ​ p (a:as) =
​  ​ IfThenElse ​ (​ EvalEven ​ (p a)) (a : ​ FindElems ​ p as) (​ FindElems ​ p as)
​  
​  ​ type ​ family ​ EQ ​ (a :: k) (b :: k) :: ​ Bool ​ ​ where ​
​  ​ EQ ​ a a = ​ True ​
​  ​ EQ ​ a b = ​ False ​
​  
​  ​ type ​ family ​ EvalEven ​ (expr :: ​ Bool ​ -> ​ Type ​) :: ​ Bool ​ ​ where ​
​  ​ EvalEven ​ (​ Even ​ n) = ​ EQ ​ 0 (n `​ Mod ​` 2)

In this example, we’ve added a closed type family to evaluate our Even type, and we’ve updated FindElems to call EvalEven to convert a ReturnValue Bool into a Bool . We also added a new helper type family, EQ , to help us test for equality between two types.

If we load this up into ghci you can see that it works as expected, and we’re able to get all of the even numbers out of a type level list:

​  ​ λ ​ :kind! ​ FindElems ​ ​ Even ​ ​ '[ ​​ 1 ​,2,3,4,5,6]
​  ​ FindElems ​ ​ Even ​ ​ '[ ​​ 1 ​,2,3,4,5,6] :: [​ Natural ​]
​  = ​ '[ ​​ 2 ​, 4, 6]

There’s still one lingering problem and one more refactor to make before we’re ready to be finished with this application. Since EvalEven is a closed type family, we’re limited to only ever using FindElems to find even numbers. If we want to give our users the ability to call FindElems with new functions we didn’t anticipate ahead of time, then we should refactor EvalEven into an open type family. Since it’ll be useful for computations other than testing for even values, we’ll also rename it Even . While we’re at it, let’s also add a new type family we can use with FindElems to find elements that are less than, or equal to, some number:

​  ​ type ​ ​ ReturnValue ​ r = r -> ​ Type ​
​  ​ data ​ ​ LessThanOrEqual ​ :: ​ Natural ​ -> ​ Natural ​ -> ​ ReturnValue ​ ​ Bool ​
​  ​ data ​ ​ Even ​ :: ​ Natural ​ -> ​ ReturnValue ​ ​ Bool ​
​  
​  ​ type ​ family ​ Eval ​ (expr :: ​ ReturnValue ​ r) :: r
​  ​ type ​ ​ instance ​ ​ Eval ​ (​ LessThanOrEqual ​ a b) = b <=? a
​  ​ type ​ ​ instance ​ ​ Eval ​ (​ Even ​ n) = ​ EQ ​ 0 (n `​ Mod ​` 2)
​  
​  ​ type ​ family
​  ​ FindElems ​ (p :: a -> ​ ReturnValue ​ ​ Bool ​) (elems :: [a]) :: [a]
​  ​ where ​
​  ​ FindElems ​ ​ _ ​ ​ '[ ​​ ] ​ = ​ '[ ​​ ] ​
​  ​ FindElems ​ p (a:as) =
​  ​ IfThenElse ​ (​ Eval ​ (p a)) (a : ​ FindElems ​ p as) (​ FindElems ​ p as)

By combining an open type family like Eval with a closed type family like FindElems , we can get the right kind of flexiblity and power that we need for more complicated type level computations. Let’s give this a try in ghci :

​  ​ λ ​ :kind! ​ FindElems ​ ​ Even ​ ​ '[ ​​ 1 ​,2,3,4,5,6]
​  ​ FindElems ​ ​ Even ​ ​ '[ ​​ 1 ​,2,3,4,5,6] :: [​ Natural ​]
​  = ​ '[ ​​ 2 ​, 4, 6]
​  
​  ​ λ ​ :kind! ​ FindElems ​ (​ LessThanOrEqual ​ 3) ​ '[ ​​ 1 ​,2,3,4,5,6]
​  ​ FindElems ​ (​ LessThanOrEqual ​ 3) ​ '[ ​​ 1 ​,2,3,4,5,6] :: [​ Natural ​]
​  = ​ '[ ​​ 1 ​, 2, 3]
​  
​  ​ λ ​ :kind! ​ FindElems ​ ​ Even ​ (​ FindElems ​ (​ LessThanOrEqual ​ 3) ​ '[ ​​ 1 ​,2,3,4,5,6])
​  ​ FindElems ​ ​ Even ​
​  (​ FindElems ​ (​ LessThanOrEqual ​ 3) ​ '[ ​​ 1 ​,2,3,4,5,6]) :: [​ Natural ​]
​  = ​ '[ ​​ 2 ​]

Working with type families to build up computations that work at the type level is a critical part of writing type level code, but there are two more important parts to working with type level programming effectively. In the next section you’ll learn about GADTs , which will let you build up type level data structures from the term level so that you can effectively generate inputs to your type level code. Finally, we’ll look at how you can use type classes to return the outputs of your type level code back to the term level for use in the rest of your application.