Sof*_*mur 5 ocaml module functor
我已经定义了一个模块类型ZONE和两个仿函数(ZoneFun和ZoneFunPrec)来构建它:
(* zone.ml *)
module type ZONE =
sig
type info
type prop
type t = { p: prop; i: info }
val f1 : t -> string
end
module ZoneFun (Prop : PROP) = struct
type info = { a: int }
type prop = Prop.t
type t = { p: prop; i: info }
let f1 z = "f1"
end
(* zoneFunPrec.ml *)
module ZoneFunPrec (Prop: PROP) (Prec: ZONESM) = struct
type info = { a: int; b: Prec.t }
type prop = Prop.t
type t = { p: prop; i: info }
let f1 z = "f1"
let get_prec z = z.info.prec
end
Run Code Online (Sandbox Code Playgroud)
这两个仿函数中的一些函数以不同的方式实现(例如f0); 一些功能完全相同(例如f1).我的问题是如何提取这些常用函数以避免两次实现它们?
编辑:(我意识到我需要提供更具体的信息,以使其更清晰......对于变更感到抱歉...)
ZoneFun和之间存在一些差异ZoneFunPrec:
1)他们type info不一样2)ZoneFunPrec 有get_prec那个ZoneFun没有,和的signture ZONE并不需要它.
所以后来我可以写module ZoneB = ZoneFun(B)和module ZoneA = ZoneFunPrec(C)(ZonesmD)建立区域......
您可以执行以下操作:
module ZoneFunPrec (Prop: PROP) = struct
module Zone1 = ZoneFun(Prop)
type prop = Prop.t
type t = string
let f0 x = "f0 in ZoneFunPrec"
let f1 = Zone1.f1
end
Run Code Online (Sandbox Code Playgroud)
但这只有在您不将签名归因于仿函数时才有效
module ZoneFunPrec (Prop: PROP) : ZONE = ...
Run Code Online (Sandbox Code Playgroud)
如果你想要不透明的归属,你可以这样做
(* No ascription here *)
module SharedFn (Prop : PROP) = struct
type prop = Prop.t
type t = string
let f0 x = "f0 in ZoneFun"
let f1 x = "f1"
end
(* Ascribe the module to hide the types *)
module ZoneFun (Prop : PROP) : ZONE = struct
module Shared = SharedFn(Prop)
let f1 = Shared.f1
...defs specific to ZONE...
end
module ZoneFunPrec (Prop: PROP) : ZONE_PREC = struct
module Shared = SharedFn(Prop)
type prop = Prop.t
type t = string
let f0 x = "f0 in ZoneFunPrec"
let f1 = Shared.f1
...defs specific to ZONE_PREC...
end
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用include Shared来节省打字,但类型将是抽象的,因此它不会很灵活。