I have a general idea of what existential quantification on types is and where it can be used. However from my experiences so far, there are a lot of caveats that need to be understood in order to use the concept effectively.
Question: Are there any good resources explaining how existential quantification is implemented in GHC? I.e.
- How does unification on existential types work – what is unifiable and what is not?
- In what order subsequent operations on types are performed?
My aim is to better understand error messages that GHC throws at me. Messages usually say something along the lines "this type using forall and this other type don't match", however they don’t explain why it is so.
The nitty-gritty details are covered in papers from Simon Peyton-Jones, though it takes a good deal of technical expertise to understand them. If you want to read a paper on how Haskell type inference works, you should read about generalized algebraic data types (GADTs), which combine existential types with several other features. I suggest “Complete and Decidable Type Inference for GADTs”, on the list of papers at http://research.microsoft.com/en-us/people/simonpj/.
Existential quantification actually works a lot like universal quantification. Here is an example to highlight the parallels between the two. The function
useExisis useless, but it’s still valid code.First, note that
toUnivandtoExisare nearly the same. They both have a free type parameterabecause both data constructors are polymorphic. But whileaappears in the return type oftoUniv, it doesn’t appear in the return type oftoExis. When it comes to the kind of type errors you might get from using a data constructor, there’s not a big difference between existential and universal types.Second, note the rank-2 type
forall a. a -> binuseExis. This is the big difference in type inference. The existential type taken from the pattern match(Exis x)acts like an extra, hidden type variable passed to the body of the function, and it must not be unified with other types. To make this clearer, here are some wrong declarations of the last two functions where we try to unify types that shouldn’t be unified. In both cases, we force the type ofxto be unified with an unrelated type variable. InuseUniv, the type variable is part of the function type. InuseExis, it’s the existential type from the data structure.