【发布时间】:2012-12-10 23:31:42
【问题描述】:
我尝试在 Ocaml 中实现这种 OO 情况:
两个类X1 和X2,都是子类型X(X1 <: X 和X2 <: X),我想编写一个动态返回X 的函数,它可以是X1 或@987654328 @。
但是我听说避免使用 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
但这在read 函数中使用Error: Unbound record field label X1.foo 失败。
我尝试了不同的排列方式,例如使用let open X1 in { foo = 0, ... },但无济于事。
我解决这个问题的方法是根本错误的(即我应该使用类,因为这对模块来说是不可能/不切实际的)还是我只是错过了一些微不足道的东西?
编辑:澄清了我要解决的问题并将module X 重命名为module XBase 以区别于module type X。
【问题讨论】:
标签: ocaml