GADTs are a new way to define data types that give us more flexibility in the ways we express our data types, and which remove some limitations in how we can define constructors that help us combine term and type level programming. They also give us a brand new syntax for defining data types. We can enable GADTs with the GADTs extension. In this section, we’ll look at how to use GADTs to define some types you’re already familiar with, and how they can be used to handle features like existential types more easily. After that, we’ll look at how GADTs fit in with type level programming, and you’ll see how to use GADTs to represent data types that couldn’t be written with traditional types.

GADTs

| images/aside-icons/info.png | The GADTs extension has been available since GHC 6.8.1. It isn’t enabled by default in either GHC2021 or Haskell2010 so you’ll need to enable it manually. This is generally a safe extension that shouldn’t interfere with any existing code. If you want to use the basic syntax of GADTs without the new type system capabilities that they add, you can also use the GADTSyntax extension, which will only enable the new syntax. GADTSyntax is enabled by default in GHC2021 but will need to be enabled manually in Haskell2010 . |

Using GADT Syntax

Let’s start learning about GADTs by rewriting a few types you’ll already be familiar with using GADT syntax. We’ll start with Maybe , Either , and a List type.

​  ​ {-# LANGUAGE GADTs #-} ​
​  ​ {-# LANGUAGE DataKinds #-} ​
​  ​ {-# LANGUAGE StandaloneDeriving #-} ​
​  ​ {-# LANGUAGE TypeOperators #-} ​
​  ​ {-# LANGUAGE KindSignatures #-} ​
​  
​  ​ module ​ ​ GADTs ​ ​ where ​
​  ​ import ​ ​ Prelude ​ ​ hiding ​ (​ Either ​(..), ​ Maybe ​(..))
​  ​ import ​ ​ Data.Kind ​
​  
​  ​ data ​ ​ Maybe ​ a ​ where ​
​  ​ Nothing ​ :: ​ Maybe ​ a
​  ​ Just ​ :: a -> ​ Maybe ​ a
​  ​ deriving ​ (​ Eq ​, ​ Show ​)
​  
​  ​ data ​ ​ Either ​ l r ​ where ​
​  ​ Left ​ :: l -> ​ Either ​ l r
​  ​ Right ​ :: r -> ​ Either ​ l r
​  
​  ​ data ​ ​ List ​ a ​ where ​
​  ​ Empty ​ :: ​ List ​ a
​  ​ Cons ​ :: a -> ​ List ​ a -> ​ List ​ a
​  ​ deriving ​ ​ Show ​

You can see in this example that GADT syntax has a strong resemblance to the closed type family syntax worked with earlier in this chapter. With GADT syntax, the constructors for our type are all listed in a where clause, and each constructor is given a type annotation that represents the type of the constructor. If you want to go even further, we can also use a kind signature instead of a type parameter in the definition of the type:

​  ​ data ​ ​ Maybe ​ :: ​ Type ​ -> ​ Type ​ ​ where ​
​  ​ Nothing ​ :: ​ Maybe ​ a
​  ​ Just ​ :: a -> ​ Maybe ​ a
​  ​ deriving ​ (​ Eq ​, ​ Show ​)

You’ll notice in this example that we’re referencing the type variable a in our constructors even though we didn’t explicitly bind it to the parameter when we defined Maybe . That’s because GADTs are much more flexible with the way we treat type variables.

GADT syntax makes working with existential types much more intuitive. For example, imagine that we wanted to define a heterogenous list of values that have a Show instance. With traditional data type syntax we’d write this:

​  ​ data ​ ​ ShowList ​ = ​ ShowEmpty ​ | forall a. ​ Show ​ a => ​ ShowList ​ a ​ ShowList ​

Writing existential types with GADT syntax more closely resembles the way we’d use constraints with a normal function definition:

​  ​ data ​ ​ ShowList ​ ​ where ​
​  ​ ShowEmpty ​ :: ​ ShowList ​
​  ​ ShowCons ​ :: ​ Show ​ a => a -> ​ ShowList ​ -> ​ ShowList ​

Even more conveniently, GADT syntax also allows us to use constraints with ordinary constructors, which saves us the need to create smart constructors if we want to restrict what values could be used with a particular type. For example, imagine we wanted to have an ordinary list that could only hold numeric values. We’d need to put our list in its own module, restrict the export list, and add a smart constructor. With GADT syntax we can simply add the constraints alongside each constructor. Unfortunately, using constraints like this means that we can’t derive type class instances in the usual way, although we can still use StandaloneDeriving to derive instances for these types:

​  ​ data ​ ​ NumList ​ a ​ where ​
​  ​ NumEmpty ​ :: ​ Num ​ a => ​ NumList ​ a
​  ​ NumCons ​ :: ​ Num ​ a => a -> ​ NumList ​ a -> ​ NumList ​ a
​  
​  ​ deriving ​ ​ instance ​ ​ Eq ​ a => ​ Eq ​ (​ NumList ​ a)
​  ​ deriving ​ ​ instance ​ ​ Show ​ a => ​ Show ​ (​ NumList ​ a)

Although it’s not very common, you can use records with GADT syntax:

​  ​ data ​ ​ MultiRecord ​ ​ where ​
​  ​ Record1 ​ ::
​  { intField :: ​ Int ​, stringField :: ​ String ​ } -> ​ MultiRecord ​
​  
​  ​ Record2 ​ ::
​  { intField :: ​ Int ​, boolField :: ​ Bool ​ } -> ​ MultiRecord ​
​  
​  ​ data ​ ​ SingleRecord ​ a ​ where ​
​  ​ SingleRecordGADT ​ ::
​  { gadtStringField :: ​ String ​
​  , gadtIntField :: ​ Int ​
​  , gadtBoolField :: ​ Bool ​
​  , gadtCustomField :: a
​  } -> ​ SingleRecord ​ a

Like traditional data types, record fields with the same name must have the same type across different constructors. You’re also not obligated to provide the same set of fields for records across each constructor. Using GADT syntax for traditional sum types with record fields can lead to the same problem of record field selectors that are partial functions. If we make use of the full features of GADTs however, we can get record field selectors that are type safe and won’t fail. In the next section you’ll learn more about how GADTs work and how they are different for regular data types, even ones defined using GADT syntax, and you’ll get a chance to see this in action.

GADTs

The key difference between GADTs and regular data types is that the type of a GADT value can be determined by the constructor that was called to create it. This is the fundamental connection between GADTs and type level programming. Since the type of a GADT value is determined by the term level function called to create it, GADTs give us a way to connect term and type level code by letting us construct the inputs to a type level program from the term level.

Before we get too far down the path of using GADTs for sophisticated type level code though, let’s look at some smaller examples to get a feel for how GADTs work. One of the best examples is the way that we can use records fields with GADTs more safely than we could with normal sum types. Imagine that we were writing a program that could recognize a user by their name or a user ID, and we wanted to get a list of all users that were identified by name and had a particular first name. Without GADTs we might write it like this:

​  ​ data ​ ​ UserNameRecord ​ =
​  ​ UserNameRecord ​ { userFirstName :: ​ String ​, userLastName :: ​ String ​ }
​  ​ data ​ ​ UserIDRecord ​ = ​ UserIDRecord ​ { userID :: ​ Int ​ }
​  ​ data ​ ​ User ​ = ​ UserByName ​ ​ UserNameRecord ​ | ​ UserByID ​ ​ UserIDRecord ​
​  
​  usersWithFirstName :: ​ String ​ -> [​ User ​] -> [​ User ​]
​  usersWithFirstName targetFirstName = filter matchingFirstName
​  ​ where ​
​  matchingFirstName nameRecord =
​  ​ case ​ nameRecord ​ of ​
​  ​ UserByName ​ (​ UserNameRecord ​ first last)
​  | first == targetFirstName -> ​ True ​
​  _otherwise -> ​ False ​

This example should look familiar; we’ve used this pattern several times in the book. We first define two helper records that hold information about users with names and users with IDs, respectively, and then we create a sum type where each constructor holds one type of user record. This adds some extra code, but it helps us avoid partial functions by avoiding having record fields directly in a sum type. When we want to search our list of user records, we might know that all of our users will be identified by name, but we still need to go through the steps to pattern match against User and then unwrap the inner UserNameRecord constructor to get at the name. Overall, we’re getting a type safe program, but paying a fairly high cost for it.

With GADTs we can encode the constructor that was used to create a UserRecord directly in the type that each constructor returns. Let’s take a look at how it works:

​  ​ data ​ ​ User ​ a ​ where ​
​  ​ UserByName ​ ::
​  { userFirst :: ​ String ​, userLast :: ​ String ​ } -> ​ User ​ ​ String ​
​  
​  ​ UserByID ​ ::
​  { userID :: ​ Int ​ } -> ​ User ​ ​ Int ​

Now that we’re using a GADT, we’ve added a type parameter to User . Unlike the earlier examples of GADT syntax though, we’re not using this type parameter to represent some field in our records. Instead, each of our constructors is selecting a different value for our parameter, a . Let’s look at this in ghci to get a better understanding of what’s going on.

We’ll start by looking at the types of UserByName and UserByID :

​  ​ λ ​ :t ​ UserByName ​
​  ​ UserByName ​ :: ​ String ​ -> ​ String ​ -> ​ User ​ [​ Char ​]
​  
​  ​ λ ​ :t ​ UserByID ​
​  ​ UserByID ​ :: ​ Int ​ -> ​ User ​ ​ Int ​

As you can see, each of our constructors returns a value with a different type. If we create a value by calling UserByID we will always get a value with the type User Int . Similarly, calling UserByName will always give us a value with the type User String . One of the ways that this is useful is that the compiler can reason about this relationship backwards as well as forwards. If we have a value with the type User String then we know that it must have been created by calling UserByName . We can see this in practice if we look at the types of our field selectors:

​  ​ λ ​ :t userFirst
​  userFirst :: ​ User ​ ​ String ​ -> ​ String ​
​  
​  ​ λ ​ :t userLast
​  userLast :: ​ User ​ ​ String ​ -> ​ String ​
​  
​  ​ λ ​ :t userID
​  userID :: ​ User ​ ​ Int ​ -> ​ Int ​

Being able to deduce the constructor, and available record fields, from the type of the user means that we can greatly simplify our filter code:

​  usersWithFirstName :: ​ String ​ -> [​ User ​ ​ String ​] -> [​ User ​ ​ String ​]
​  usersWithFirstName firstName = filter ((== firstName) . userFirst)

Although it’s useful to be able to differentiate between different types of users at the type level, this also ends up presenting us with a different problem. Since constructing a user by name and by ID results in a different type, we also can’t create a list of name and ID users.

A Heterogenous User List

Earlier in this book you learned about using existential types as a way of creating heterogenous lists, but that approach came with a substantial cost: once a value was inserted into a list of existential typed values, we could never recover the original type and were limited to accessing the values through type classes.

It turns out that GADTs can give us another option for working with heterogenous lists that don’t limit us in the same way that existential-based lists do, although it comes at the cost of needing to do some type level programming.

Let’s start by taking a look at how we can use GADTs to define a heterogenous user list:

​  ​ {-# LANGUAGE DataKinds #-} ​
​  
​  ​ infixr ​ 9 :++:
​  ​ data ​ ​ Heterogenous ​ a ​ where ​
​  ​ EmptyUsers ​ :: ​ Heterogenous ​ ​ '[ ​​ ] ​
​  (:++:) :: ​ User ​ a -> ​ Heterogenous ​ as -> ​ Heterogenous ​ (a : as)

Unlike existential-based heterogenous lists, our GADT approach uses a straightforward, if somewhat brute force, approach to retaining the detailed type information for every element in the list. Our list has a type parameter that is itself a list of the type of every element that has been inserted into the list. Each time we add a new value, we also add its type to the type of the list. Let’s load up ghci and take a look to get an idea of what this means in practice:

​  ​ λ ​ byName = ​ UserByName ​ ​ "Georgie" ​ ​ "Bird" ​
​  ​ λ ​ byID = ​ UserByID ​ 12345
​  ​ λ ​ :​ type ​ ​ EmptyUsers ​
​  ​ EmptyUsers ​ :: ​ Heterogenous ​ ​ '[ ​​ ] ​
​  
​  ​ λ ​ :​ type ​ byName :++: ​ EmptyUsers ​
​  byName :++: ​ EmptyUsers ​ :: ​ Heterogenous ​ ​ '[ ​​ [ ​​ Char ​]]
​  
​  ​ λ ​ :​ type ​ byID :++: byID :++: byName :++: ​ EmptyUsers ​
​  byID :++: byID :++: byName :++: ​ EmptyUsers ​
​  :: ​ Heterogenous ​ ​ '[ ​​ I ​nt, ​ Int ​, [​ Char ​]]

As you can see, each time we add a new user type to the list, the type of the list changes to keep track of the new information. That means the information is always entirely recoverable.

Extracting Fields from a Heterogenous List

If we have all of the type information for each element that we’ve inserted into our user list, then we ought to be able to use that to recover specific fields. Let’s imagine that we wanted to extract a list of the users who are identified by name from a heterogenous list of users. How might we approach that? Once again GADTs help make this easy. Let’s look at the code:

​  nameUsers :: ​ Heterogenous ​ a -> [​ User ​ ​ String ​]
​  nameUsers ​ EmptyUsers ​ = ​ [] ​
​  nameUsers (user :++: users) =
​  ​ case ​ user ​ of ​
​  ​ UserByName ​ ​ _ ​ ​ _ ​ -> user : nameUsers users
​  ​ UserByID ​ ​ _ ​ -> nameUsers users

Since the type of Heterogenous a carries all of the type information that we need, we’re able to pattern match on each element of the list. The constructor used to create each element also tells us the type of that element, and so we can select all of the values with the type User String .

A GADT-Based Shell Command Wrapper

Being able to determine the type of a value by the constructor used to create it is a powerful technique, but our user example only scratches the surface. Let’s return to our ShellCommand example and look at how GADTs can allow us to write an easier to use and more expressive language for writing shell scripts.

Earlier in this chapter, you wrote a small library to help a user write shell scripts in their Haskell applications. In that example, we used a type class called ShellCommand , along with an associated type family to describe a particular command.

This approach had the benefit of extensibility, and we were able to define several different operations that we could run. We could even compose our operations together by defining a Pipe and creating a ShellCommand instance for it. The type class approach also had some drawbacks. The biggest drawback is that each shell command was its own type. Composing commands required creating a new type, and there was nothing to limit a users ability to create an invalid or poorly behaved instance of ShellCommand .

GADTs allow us to implement ShellCommand as a small internal library that gives us many of the same benefits of the type class approach. Let’s look at a complete reimplementation of our earlier DSL using GADTs, and then walk through how it works step by step.

​  ​ {-# LANGUAGE TypeFamilies #-} ​
​  ​ {-# LANGUAGE GADTs #-} ​
​  ​ module ​ ​ GADTShellCmd ​ ​ where ​
​  ​ import ​ ​ System.FilePath.Posix ​ ((</>))
​  ​ import ​ ​ System.Process ​ (​ readProcess ​)
​  ​ import ​ ​ System.IO.Error ​
​  
​  ​ newtype ​ ​ ProgName ​ = ​ ProgName ​ { getProgName :: ​ FilePath ​ }
​  ​ newtype ​ ​ ProgArgs ​ = ​ ProgArgs ​ { getProgArgs :: [​ String ​] }
​  
​  ​ data ​ ​ ShellCmd ​ a b ​ where ​
​  ​ RunCommand ​ ::
​  ​ ProgName ​ -> (a -> ​ ProgArgs ​) -> (a -> ​ String ​ -> b) -> ​ ShellCmd ​ a b
​  ​ Pipe ​ :: ​ ShellCmd ​ a b -> ​ ShellCmd ​ b c -> ​ ShellCmd ​ a c
​  ​ XArgs ​ :: ​ ShellCmd ​ a b -> ​ ShellCmd ​ [a] [b]
​  ​ MapOut ​ :: (b -> c) -> ​ ShellCmd ​ b c
​  
​  ​ data ​ ​ GrepMatch ​ = ​ GrepMatch ​
​  { grepMatchingFileName :: ​ FilePath ​
​  , grepMatchingLineNumber :: ​ Int ​
​  , grepMatchingLineContents :: ​ String ​
​  } ​ deriving ​ (​ Eq ​, ​ Show ​)
​  
​  grep :: ​ String ​ -> ​ ShellCmd ​ ​ FilePath ​ [​ GrepMatch ​]
​  grep matchGlob =
​  ​ RunCommand ​ (​ ProgName ​ ​ "grep" ​) makeArgs parseLines
​  ​ where ​
​  makeArgs fileName = ​ ProgArgs ​ $ ​ "-n" ​ : matchGlob : [fileName]
​  parseLines fileName = map (parseResponse fileName) . lines
​  parseResponse fileName responseLine =
​  ​ let ​ (matchNumber, contents) = span (/= ​ ':' ​) responseLine
​  ​ in ​ ​ GrepMatch ​ fileName (read matchNumber) contents
​  
​  listDirectory :: ​ ShellCmd ​ ​ FilePath ​ [​ FilePath ​]
​  listDirectory =
​  ​ RunCommand ​ (​ ProgName ​ ​ "ls" ​) makeArgs parseResponse
​  ​ where ​
​  makeArgs filePath = ​ ProgArgs ​ [​ "-1" ​, filePath]
​  parseResponse filePath =
​  map (filePath </>) . lines
​  
​  runShellCmd :: ​ ShellCmd ​ a b -> a -> ​ IO ​ b
​  runShellCmd cmd input =
​  ​ case ​ cmd ​ of ​
​  ​ RunCommand ​ (​ ProgName ​ exeName) mkArgs parseOut ->
​  parseOut input <$> catchIOError processOut (const $ pure ​ "" ​)
​  ​ where ​
​  processOut = readProcess exeName (getProgArgs $ mkArgs input) ​ "" ​
​  ​ Pipe ​ inputCmd out -> runShellCmd inputCmd input >>= runShellCmd out
​  ​ XArgs ​ inputCmd -> mapM (runShellCmd inputCmd) input
​  ​ MapOut ​ mapF -> pure $ mapF input

You can start to see the benefits of GADTs more clearly in this example if we look at the way that letting each constructor determine the type of the output allows us to build a DSL that ensures we’re composing individual parts of our shell command in a type safe way. For example, the Pipe constructor allows us to create a pipe from two ShellCmd values, but only if the output of the first command matches the input of the second. The result of the Pipe constructor is a new ShellCmd that takes the input needed for the first sub-command, and returns the output of the second sub-command. This is an improvement over our earlier pipe implementation because it allows us to more directly compose individual commands, rather than needing to create an explicit function to map the results of the first command to the second.

The next major difference between our GADT-based approach and our earlier type class approach is that we’ve added two new constructors, XArgs and MapOut . The XArgs constructor allows us to take a shell command that would run on a single argument, and instead run it on a list of inputs. This is an example of a feature that would have been much harder to implement with our type class based approach. Were we using type classes, we would have needed to add an extra associated type family to handle the different input types of each command, and then we would need to add that type family to each instance we’d defined.

The next constructor, MapOut , is another example of a feature that is much easier for us to add thanks to our use of GADTs. This constructor lets us lift a pure function and treat it as a ShellCmd . This wouldn’t have fit well with the runCmd function we defined in our ShellCommand class, since it relies on a polymorphic input type that, like XArgs , would have required an extra type family be added to the class. Worse, MapOut can’t provide any useful command name or arguments, and so our application may have encountered a runtime error when it tried to execute an empty command.

Once our ShellCmd GADT is defined, you’ll notice that the definitions of grep and listDirectory are largely unchanged. We have a very similar level of expressive power for defining individual commands, while gaining a great deal of composability thanks to our GADT-based types.

The last major difference in this example is the definition of runShellCmd . Instead of calling the runCmd function from a type class, we’re pattern matching on each constructor. Take particular note of the way we handle XArgs in this function:

​  runShellCmd :: ​ ShellCmd ​ a b -> a -> ​ IO ​ b
​  runShellCmd cmd input =
​  ​ -- ... ​
​  ​ XArgs ​ inputCmd -> mapM (runShellCmd inputCmd) input

What’s interesting about this case is that we’re calling mapM over input even though the type of runShellCmd doesn’t specify that input must be a list. Thanks to GADTs though, we know that XArgs will always result in a ShellCmd that accepts a list and returns a list, so any time we match on the XArgs case we can guarantee that in that particular case, input will be a list.