Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The type constructor "..." would escape its scope when using first class modules

Given a simple factory:

module type Factory  = sig type t val create : unit -> t end
module FactoryImpl : Factory = struct 
   type t = string
   let create: unit -> t = fun ()  -> "aaa" 
end 
let factory: (module Factory) = (module FactoryImpl)
let f = let module F = (val factory) in F.create ()

Compiler complains:

This has type:
F.t
But somewhere wanted:
F.t
The type constructor F.t would escape its scope

I am quite new to OCaml modules and not sure how to tell compiler that f is of type Factory.t

like image 304
mbergal Avatar asked Jul 09 '18 22:07

mbergal


1 Answers

The problem here is that F.create () produces a value of type F.t, so f should have type F.t, but that is impossible because F is not bound outside the let module that binds F.

If you extend the scope of F to be global, the program will type check:

module type Factory = sig
  type t
  val create : unit -> t
end

module FactoryImpl : Factory = struct
  type t = string
  let create: unit -> t = fun () -> "aaa"
end

let factory: (module Factory) = (module FactoryImpl)

module F = (val factory)

let f = F.create ()

Note that Factory.t is not a valid type, as there is no module bound to the name Factory. Modules and module types are in separate namespaces.

like image 182
gsg Avatar answered Oct 15 '22 20:10

gsg