简体   繁体   中英

OCaml functor taking polymorphic variant type

Trying to compile

module F (M : sig
  type t = [> `Foo ]
end) = struct
  type t = [ M.t | `Bar ]
end

gets me

Error: A type variable is unbound in this type declaration.
In type [> `Foo ] as 'a the variable 'a is unbound

What am I doing wrong?

type t = [> `Foo] is invalid since [> `Foo] is an open type and contains a type variable implicitly. The definition is rejected just as the following type definition is rejected since the RHS has a type variable which is not quantified in LHS:

type t = 'a list

You have to make it closed:

type t = [ `Foo ]

or quantify the type variable:

type 'a t = [> `Foo] as 'a

which is equivalent to

type 'a t = 'a constraint 'a = [> `Foo]

This seems to work:

module F ( M : sig
  type base_t = [ `Foo ]
  type 'a t = [> base_t] as 'a
end) = struct
  type t = [ M.base_t | `Bar ] M.t
end

M.base_t is closed, while Mt('a) is polymorphic. F constructs Mt using M.base_t extended with 'Bar .

Here is reasonml try link , which includes the snippet above both in OCaml and ReasonML syntax, and proves that it compiles.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM