OCaml GADTs
Generalized algebraic data types (GADTs) are variants in which each constructor can give the type a more specific type parameter. They let the type checker know more about a value after you match on it. This is an advanced feature, and you can write a lot of OCaml without it, but it is good to recognise.
The problem GADTs solve
Here is an ordinary expression type that mixes ints and bools:
type value = VInt of int | VBool of bool
type expr =
| Int of int
| Bool of bool
| Add of expr * expr
| If of expr * expr * expr
| Eq of expr * exprNothing stops you from writing Add (Bool true, Int 3), so eval must return a value and check types at run time, failing on nonsense. With a GADT, the expression's type becomes part of its OCaml type, and nonsense does not compile.
A typed expression language
GADT constructors are declared with an explicit result type after ::
type _ expr =
| Int : int -> int expr
| Bool : bool -> bool expr
| Add : int expr * int expr -> int expr
| Eq : int expr * int expr -> bool expr
| If : bool expr * 'a expr * 'a expr -> 'a expr
| Pair : 'a expr * 'b expr -> ('a * 'b) expr
let rec eval : type a. a expr -> a = function
| Int n -> n
| Bool b -> b
| Add (x, y) -> eval x + eval y
| Eq (x, y) -> eval x = eval y
| If (c, t, e) -> if eval c then eval t else eval e
| Pair (a, b) -> (eval a, eval b)
let () =
let price = Add (Int 40, Int 2) in
let check = If (Eq (price, Int 42), Bool true, Bool false) in
let both = Pair (price, check) in
let n, ok = eval both in
Printf.printf "%d %b\n" (eval price) (eval check);
Printf.printf "%d %b\n" n ok42 true
42 true
Look at what happened:
Int 3has typeint expr;Eq (...)has typebool expr.evalreturns a plainintfor anint exprand a plainboolfor abool expr: no wrapper type, no run-time type checks.- The annotation
type a. a expr -> ais required. It declares a locally abstract typeathat is refined in each branch: in theInt nbranch the compiler knowsa = int.
Ill-typed programs are rejected
type _ expr =
| Int : int -> int expr
| Bool : bool -> bool expr
| Add : int expr * int expr -> int expr
let bad = Add (Int 1, Bool true)
let () = ignore badFile "<source>", line 6, characters 22-31:
6 | let bad = Add (Int 1, Bool true)
^^^^^^^^^
Error: This constructor has type bool expr
but an expression was expected of type int expr
Type bool is not compatible with type int
The error is found at compile time, before any evaluation.
Existential types: hiding a type
A GADT constructor can also mention a type variable that does not appear in its result. That type is then hidden ("existential"). This lets you put values of different types in one list, as long as each comes with the functions needed to use it:
type printable = Show : 'a * ('a -> string) -> printable
let items =
[ Show (42, string_of_int);
Show ("camel", fun s -> "\"" ^ s ^ "\"");
Show ([ 1.5; 2.5 ], fun l -> "[" ^ String.concat "; " (List.map string_of_float l) ^ "]") ]
let () = List.iter (fun (Show (v, to_s)) -> print_endline (to_s v)) items42
"camel"
[1.5; 2.5]
Inside the match, the code knows that v and to_s agree on some type, but not which one, so the only thing it can do is apply to_s to v. That is exactly the safety we want.
Typed keys: a heterogeneous store
A final pattern: a GADT for keys that each carry the type of their value.
type _ setting =
| Port : int setting
| Host : string setting
| Debug : bool setting
let default : type a. a setting -> a = function
| Port -> 8080
| Host -> "localhost"
| Debug -> false
let describe : type a. a setting -> a -> string =
fun key v ->
match key with
| Port -> "port=" ^ string_of_int v
| Host -> "host=" ^ v
| Debug -> "debug=" ^ string_of_bool v
let () =
print_endline (describe Port (default Port));
print_endline (describe Host "example.org");
print_endline (describe Debug (not (default Debug)))port=8080
host=example.org
debug=true
default Port has type int and default Host has type string, from a single function.
When to use GADTs
| Good uses | Prefer something simpler when |
|---|---|
| typed interpreters and DSLs | a plain variant is enough |
format strings (OCaml's Printf is built on GADTs) |
you just need polymorphism ('a list) |
| typed keys, heterogeneous containers | error messages matter more than extra guarantees |
GADTs make type errors harder to read and need annotations, so use them where the extra precision really pays off.
Test yourself
What is special about a GADT constructor such as Eq : int expr * int expr -> bool expr?
- It is mutable
- It fixes the type parameter of the result to a specific type
- It can only hold ints
- It raises an exception
Why does eval need the annotation type a. a expr -> a?
- For performance
- So the compiler can refine the locally abstract type
ain each branch - Because GADTs cannot be printed
- It is optional style
In type printable = Show : 'a * ('a -> string) -> printable, what is 'a?
- Always string
- An existential type hidden inside the value
- A syntax error
- The same as printable