module - 从 2 个仿函数中提取常用函数

标签 module ocaml functor

我定义了一个模块类型ZONE和两个仿函数( ZoneFunZoneFunPrec )来构建它:

(* 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) ZoneFunPrecget_precZoneFun没有,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/

相关文章:

javascript - 在 webpack 2 中使用自己的模块

php - Magento 模型不会保存值

ocaml - OCaml 中的参数化类型

scala - 如何将 Haskell 翻译成 Scalaz?

haskell - Last 是一个自由幺半群吗?

c++ - 仿函数和字符串 vector

javascript - 更改模块名称大小写时,Webpack 使 bundle 无效

python - 如何导入一个模块的所有功能?

ocaml - 组合列表中的元素-OCaml

ocaml - 生成的折叠类型、迭代器和映射与 ppx_deriving 文档不一致