我定义了一个模块类型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
这 2 个仿函数中的一些函数的实现方式不同(例如
f0
);某些功能完全相同(例如 f1
)。我的问题是如何提取这些常用功能以避免两次实现它们?编辑: (我意识到我需要提供更具体的信息以使其更清楚......抱歉改变......)
ZoneFun
之间存在一些差异和 ZoneFunPrec
:1) 他们的
type info
不一样2)
ZoneFunPrec
有 get_prec
那ZoneFun
没有,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
但这只有在您不在仿函数中赋予签名时才有效
module ZoneFunPrec (Prop: PROP) : ZONE = ...
如果你想要不透明的归属,你可以做这样的事情
(* 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
您可以尝试使用
include Shared
节省打字,但类型将是抽象的,所以它不会很灵活。
关于module - 从 2 个仿函数中提取常用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18721357/