Skip to content

Instantly share code, notes, and snippets.

@Risto-Stevcev
Forked from infinity0/test.ml
Created July 31, 2018 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Risto-Stevcev/03624fc5f09ba57a31d487f172919cec to your computer and use it in GitHub Desktop.
Save Risto-Stevcev/03624fc5f09ba57a31d487f172919cec to your computer and use it in GitHub Desktop.
OCaml GADTs and avoiding "type constructor would escape its scope" errors
(* GADT list that exposes the type of the head element *)
type _ hlist =
| Nil: 'a hlist
| Cons: ('a * 'b hlist) -> 'a hlist
(* let rec len = function *)
(* let rec len (type a) (l: a hlist): int = match l with *)
(* both of the above result in a "type constructor would escape its scope" error *)
(* correct version: *)
let rec len : type a. a hlist -> int = function
(* also correct: *)
(* let rec len : 'a. 'a hlist -> int = function *)
| Nil -> 0
| Cons (h, t) -> 1 + len t
(* NB: this only works if you don't extract your elements.
if you need to extract the elements then the error is real, and you either need to redesign your code
so that the inner types (to be extracted) are contained in the outer type param *)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment