OCaml functor with polymorphic variant

Attempting 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?

+6


source to share


2 answers


type t = [> `Foo]

invalid because it [> `Foo]

is an open type and implicitly contains a type variable. The definition is rejected in the same way that the definition of the next type is rejected because the RHS has a type variable that is not quantified in the LHS:

type t = 'a list

      

You have to close it:

type t = [ `Foo ]

      



or quantify a variable of type:

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

      

which is equivalent

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

      

+5


source


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

closed, but Mt('a)

polymorphic. F

builds Mt

using M.base_t

advanced with 'Bar

.

Here is a mindml try link that includes the above code snippet in OCaml and ReasonML syntax and proves that it compiles.

0


source







All Articles