如何定义模块实现由仿函数参数化的模块签名

cod*_*nk1 6 ocaml functional-programming module functor

假设我有一个模块M参数化的模块F:

module M (F : sig type id type data end) =
struct
 type idtype = F.id
 type datatype = F.data
 type component = { id : idtype; data : datatype }
 let create id data = { id; data }
 let get_comp_data comp = comp.data
 let get_comp_id comp = comp.id
end
Run Code Online (Sandbox Code Playgroud)

所以我这样使用它:

module F1 = struct type id = int type data = float end
module MF1 = M(F1)

let comp = MF1.create 2 5.0
let id = MF1.get_comp_id comp
Run Code Online (Sandbox Code Playgroud)

现在,如果我想M匹配签名S:

module type S = 
sig
  type idtype
  type datatype 
  type component
  val create : idtype -> datatype -> component
  val get_comp_data : component -> datatype
  val get_comp_id : component -> idtype
end

module F1 = struct type id = int type data = float end
module MF1 = (M(F1) : S)

let comp = MF1.create 2 5.0
let id = MF1.get_comp_id comp
Run Code Online (Sandbox Code Playgroud)

让我困扰这里,为了定义get_comp_dataget_comp_id,我需要指定idtypedatatype模块S; 现在想象一下,我有其他类型的记录类型M,我将指定十几种类型S?有没有更简单的方法来避免这种情况?

And*_*erg 9

这样做的自然方法是将模块密封在定义站点,而不是使用站点.然后你只需要表达一次类型共享:

module M (F : sig type id type data end) :
  S with type idtype = F.id and datatype = F.data
  = struct ... end
Run Code Online (Sandbox Code Playgroud)

如果您的仿函数参数更复杂,那么您也可以只共享整个模块而不是单个类型.例如:

module type TYPES = sig type id type data (* ...and more... *) end

module type S = 
sig
  module Types : TYPES
  type component
  val create : Types.id -> Types.data -> component
  val get_comp_data : component -> Types.data
  val get_comp_id : component -> Types.id
end

module M (F : TYPES) : S with module Types = F
  = struct ... end
Run Code Online (Sandbox Code Playgroud)

或者您甚至可以通过将其嵌套到另一个仿函数中来对签名本身进行参数化:

module type TYPES = sig type id type data (* ...and more... *) end

module S (F : TYPES) =
struct
  module type S =
  sig
    type component
    val create : F.id -> F.data -> component
    val get_comp_data : component -> F.data
    val get_comp_id : component -> F.id
  end
end

module M (F : TYPES) : S(F).S
  = struct ... end
Run Code Online (Sandbox Code Playgroud)