-
-
Save Risto-Stevcev/03624fc5f09ba57a31d487f172919cec to your computer and use it in GitHub Desktop.
OCaml GADTs and avoiding "type constructor would escape its scope" errors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* 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