I ran into a pretty simple OCaml problem, but I cannot find an elegant solution. I work with functors that apply to relatively simple modules (they usually define the type and several functions of this type) and extend these simple modules by adding additional more complex functions, types and modules. Simplified version:
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
There is no need to specify the name of a simple module, because all its functions are present in the extended module, and functions in the simple module are generated by camlp4 based on the type. Idiomatic use of these functors:
module Int = Complex(struct
type t = int
end)
The problem occurs when I work with records:
module Point2D = Complex(struct
type t = { x : int ; y : int }
end)
let (Some location) = Point2D.read db "location"
There seems to be no easy way to access the fields xand y, as defined above, outside the module Point2D, like location.xor location.Point2D.x. How can I achieve this?
: , :
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 } (* <
end)
let _ = (Made.get None).a (* <