我有这种 OO 情况,我试图在 Ocaml 中实现:两个类X1和X2,都是子类型X(X1 <: X和X2 <: X),我想编写一个动态返回一个的函数,X它可以是 anX1或 an X2。
但是我听说避免使用 Ocaml 中的类并改用模块通常很好,所以我试图像这样表示我的问题(过于简化但仍然很重要):两个模块X1和X2,我希望我的函数在返回一个X1.t或一个X2.t。
module type X = sig
type choice
type t
(* some methods we don't care about in this instance, like
val modifySomething : t -> t *)
end
module Xbase = struct
type choice = Smth | SmthElse
end
module X1 = (
struct
include Xbase
type t = { foo : int; bar : int }
end : X)
module X2 = (
struct
include Xbase
type t = { foo : int; star : int }
end : X)
module XStatic =
struct
(* construct either an X1.t or X2.t from the string *)
let read : string -> 'a =
function
| "X1" -> { X1.foo = 0, bar = 0 }
| "X2" -> { X2.foo = 1, star = 1 }
end
但这Error: Unbound record field label X1.foo在read功能中失败了。我尝试了不同的排列方式,例如使用let open X1 in { foo = 0, ... }但无济于事。
我的方法是从根本上错误的(即我应该使用类,因为这对模块来说是不可能/不切实际的)还是我只是错过了一些微不足道的东西?
编辑:澄清了我要解决的问题并重命名module X为module XBase以区别于module type X.