我偶然发现了一个相当简单的OCaml问题,但我似乎无法找到一个优雅的解决方案。我正在研究应用于相对简单的模块的函子(它们通常在该类型上定义类型和几个函数),并通过添加更多更复杂的函数,类型和模块来扩展这些简单模块。一个简化的版本将是:模块和记录字段
module type SIMPLE = sig
type t
val to_string : t -> string
val of_string : string -> t
end
module Complex = functor (S:SIMPLE) -> struct
include S
let write db id t = db # write id (S.to_string t)
let read db id = db # read id |> BatOption.map S.of_string
end
没有必要,得到单模的名称,因为其所有的功能存在于扩展的模块中,并且简单模块中的功能由camlp4基于类型产生的。在习惯使用这些仿函数是:
module Point2D = Complex(struct
type t = { x : int ; y : int }
end)
let (Some location) = Point2D.read db "location"
似乎有被访问x
和y
领域没有简单的方法,从上述定义:
module Int = Complex(struct
type t = int
end)
当我与记录工作出现问题Point2D
模块之外,如location.x
或location.Point2D.x
。我怎样才能做到这一点?
编辑:根据要求,这里显示的问题一个完整的小例子:
所有的module type TYPE = sig
type t
val default : t
end
module Make = functor(Arg : TYPE) -> struct
include Arg
let get = function None -> default | Some x -> (x : t)
end
module Made = Make(struct
type t = {a : int}
let default = { a = 0 } (* <-- Generated by camlp4 based on type t above *)
end)
let _ = (Made.get None).a (* <-- ERROR *)
发布可编译代码将非常有助于获得可编译的答案。 –