8.7 Recovering the type of a module

(Introduced in OCaml 3.12)

module-type::=
module type of module-expr

The construction moduletypeofmodule-expr expands to the module type(signature or functor type) inferred for the module expression module-expr.To make this module type reusable in many situations, it isintentionally not strengthened: abstract types and datatypes are notexplicitly related with the types of the original module.For the same reason, module aliases in the inferred type are expanded.

A typical use, in conjunction with the signature-level includeconstruct, is to extend the signature of an existing structure.In that case, one wants to keep the types equal to types in theoriginal module. This can done using the following idiom.

  1. module type MYHASH = sig
  2. include module type of struct include Hashtbl end
  3. val replace: ('a, 'b) t -> 'a -> 'b -> unit
  4. end
  5.  

The signature MYHASH then contains all the fields of the signatureof the module Hashtbl (with strengthened type definitions), plus thenew field replace. An implementation of this signature can beobtained easily by using the include construct again, but thistime at the structure level:

  1. module MyHash : MYHASH = struct
  2. include Hashtbl
  3. let replace t k v = remove t k; add t k v
  4. end
  5.  

Another application where the absence of strengthening comes handy, isto provide an alternative implementation for an existing module.

  1. module MySet : module type of Set = struct
  2. end
  3.  

This idiom guarantees that Myset is compatible with Set, but allowsit to represent sets internally in a different way.