undefined
.
Eventually, the complete
version will be made available.
GADTs
Today we are going to talk about some of my favorite GHC extensions.
Generalized Algebraic Datatypes, or GADTs, are one of GHC's more advanced extensions to Haskell. In this lecture, we introduce GADTs and related features of the type system.
An Untyped Expression Evaluator
As a motivating example, here is a standard datatype of integer and boolean expressions.
> data OExp =
> OInt Int -- a number constant, like '2'
> | OBool Bool -- a boolean constant, like 'true'
> | OAdd OExp OExp -- add two expressions, like 'e1 + e2'
> | OIsZero OExp -- test if an expression is zero
> | OIf OExp OExp OExp -- if expression, 'if e1 then e2 else e3'
> deriving (Eq, Show)
And here is an evaluator for these expressions. Note that the result type of this interpreter could either be a boolean or an integer value.
> oevaluate :: OExp -> Maybe (Either Int Bool)
> oevaluate (OInt i) = Just (Left i)
> oevaluate (OBool b) = Just (Right b)
> oevaluate (OAdd e1 e2) =
> case (oevaluate e1, oevaluate e2) of
> (Just (Left i1), Just (Left i2)) -> Just (Left (i1 + i2))
> _ -> Nothing
> oevaluate (OIsZero e1) =
> case oevaluate e1 of
> Just (Left x) -> if x == 0 then Just (Right True) else Just (Right False)
> _ -> Nothing
> oevaluate (OIf e1 e2 e3) =
> undefined
Ugh. That Maybe/Either combination is awkward.
Plus, this language admits some strange terms:
A Typed Expression Evaluator
As a first step, let's rewrite the definition of the expression datatype in so-called "GADT syntax":
> data SExp where
> SInt :: Int -> SExp
> SBool :: Bool -> SExp
> SAdd :: SExp -> SExp -> SExp
> SIsZero :: SExp -> SExp
> SIf :: SExp -> SExp -> SExp -> SExp
We haven't changed anything yet -- this version means exactly the same as the definition above. The change of syntax makes the types of the constructors -- in particular, their result type -- more explicit in their declarations. Note that, here, the result type of every constructor is SExp
, and this makes sense because they all belong to the SExp
datatype.
Now let's refine it:
> data GExp :: * -> * where
> GInt :: Int -> GExp Int
> GBool :: Bool -> GExp Bool
> GAdd :: GExp Int -> GExp Int -> GExp Int
> GIsZero :: GExp Int -> GExp Bool
> GIf :: GExp Bool -> GExp a -> GExp a -> GExp a
Note what's happened: every constructor still returns some kind of GExp
, but the type parameter to GExp
is sometimes refined to something more specific than a
.
Check out the type errors that result if you uncomment these expressions.
Now we can give our evaluator a more exact type and write it in a much clearer way:
> evaluate :: GExp t -> t
> evaluate (GInt i) = i
> evaluate (GBool b) = b
> evaluate (GAdd e1 e2) = evaluate e1 + evaluate e2
> evaluate (GIsZero e1) =
> undefined
> evaluate (GIf e1 e2 e3) =
> undefined
Not only that, our evaluator is more efficient [1] because it does not need to wrap the result in the Maybe
and Either
datatypes.
GADTs with DataKinds
Let's look at one more simple example, which also motivates another GHC extension that is often useful with GADTs.
We have seen that kinds describe types, just like types describe terms. For example, the parameter to T
below must have the kind of types with one parameter, written * -> *
. In other words, a
must be like Maybe
or []
.
Check your understanding. What is the kind of T
? To find out, you can ask ghci.
ghci> :kind T
The "datakinds" extension of GHC allows us to use datatypes as kinds. For example, this type, U
is parameterized by a boolean.
That means that the kind of U
is Bool -> *
. In other words, both U 'True
[2] and U 'False
are valid types for MkU
(and different from eachother).
Right now, U
doesn't seem very useful as it doesn't tell us very much. So let's look at a more informative GADTs.
Consider a version of lists where the flag indicates whether the list is empty or not. To keep track, let's define a flag for this purpose...
...and then use it to give a more refined definition of lists.
As we saw above, GADTs allow the result type of data constructors to vary. In this case, we can give Nil
a type that statically declares that the list is empty.
> data List :: Flag -> * -> * where
> Nil :: List Empty a
> Cons :: a -> List f a -> List NonEmpty a
Analogously, the type of Cons
reflects that it creates a nonempty list. Note that the second argument of Cons
can have either flag -- it could be an empty or nonempty list.
Note, too, that in the type List Empty a
, the type Flag
has been lifted to a kind (i.e., it is allowed to participate in the kind expression Flag -> * -> *
), and the value constructor Empty
is now allowed to appear in the type expression List Empty a
.
(What we're seeing is a simple form of dependent types, where values are allowed to appear at the type level.)
The payoff for this refinement is that, for example, the head
function can now require that its argument be a nonempty list. If we try to give it an empty list, GHC will report a type error.
Compare this definition to the unsafe version of head.
(In fact, including a case for Nil
is not only not needed: it is not allowed!)
This flag doesn't interact much with some of the list functions. For example, foldr
works for both empty and nonempty lists.
But the foldr1
variant (which assumes that the list is nonempty and omits the "base" argument) can now require that its argument be nonempty.
> foldr1' :: (a -> a -> a) -> List NonEmpty a -> a
> foldr1' f (Cons x Nil) = x
> foldr1' f (Cons x y@(Cons _ _)) = f x (foldr1' f y)
Note that, in the second pattern we have to explicitly match against Cons
in the @
pattern because the type checker does not track the order of the definition clauses when GADTs are used. So it doesn't know that xs
can only be a Cons
at this point.
The type of map
becomes stronger in an interesting way: It says that we take empty lists to empty lists and nonempty lists to nonempty lists. If we forgot the Cons
in the last line, the function wouldn't type check. (Though, sadly, it would still type check if we had two Cons
es instead of one.)
For filter
, we don't know whether the output list will be empty or nonempty. (Even if the input list is nonempty, the boolean test might fail for all elements.) So this type doesn't work:
(Try to implement the filter function and see where you get stuck!)
This type also doesn't work...
... because f'
here is unconstrained, i.e., this type says that filter'
will return any f'
. But that is not true: it will return only one f'
for a given input list -- we just don't know what it is!
The solution is to hide the size flag in an auxiliary datatype
To go in the other direction -- from OldList
to List
-- we just use pattern matching. For example:
Now we can use OldList
as the result of filter'
, with a bit of additional pattern matching.
Although these examples are simple, GADTs and DataKinds can also work in much larger libraries, especially to simulate the effect of dependent types [3].
Lecture notes
[1] The OCaml language also includes GADTs. See this blog post about how Jane Street uses them to optimize their code.
[2] When data constructors are used in types, we often add a '
in front of them. This mark tells GHC that it should be looking for a data constructor (like True
) instead of a type constructor (like Bool
). GHC won't complain if you leave this tick off as long as there is no overloading of data constructor and type constructor names. However, consider []
, and ()
, and (,)
. These all stand for both data constructors (i.e. the empty list, the unit value, and the pairing constructor) and type constructors (i.e. the list type constructor, the unit type, and the pairing type constructor). So if you are using these to index GADTS, you must always use a tick when you mean the data constructor.
[3] Galois, a Haskell-based company, makes heavy use of these features in their code base and has written up a short paper about their experiences.