ocaml - 我可以从运行时选择的 OCaml 类继承吗?

标签 ocaml

所以现在我有两个相同类类型的类,例如

class foo : foo_type = object ... end

class bar : foo_type = object ... end

我想要一个继承自 foo 的第三个类。或 bar在运行时。例如。 (伪语法)
class baz (some_parent_class : foo_type) = object
    inherit some_parent_class
    ...
end

这在 OCaml 中可能吗?

用例:我正在使用对象来构建 AST 访问者,并且我希望能够根据一组运行时标准组合这些访问者,以便它们只对 AST 进行一次组合遍历。

编辑:我想我已经找到了一种使用一流模块创建所需类的方法:
class type visitor_type = object end

module type VMod = sig
  class visitor : visitor_type
end

let mk_visitor m =
  let module M = (val m : VMod) in
  (module struct
    class visitor = object
      inherit M.visitor
    end
  end : VMod)

然而,为了使其成为“一流”,必须将一个类包装在一个模块中似乎有点迂回。如果有更直接的方法请告诉我。

最佳答案

这只是您已经建议的更清洁的实现,但我会这样做:

module type Foo = sig
  class c : object
    method x : int
  end
end

module A = struct
  class c = object method x = 4 end
end

module B = struct
  class c = object method x = 5 end
end

let condition = true

module M = (val if condition then (module A) else (module B) : Foo)

class d = object (self)
  inherit M.c
  method y = self#x + 2
end

关于ocaml - 我可以从运行时选择的 OCaml 类继承吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28612989/

相关文章:

functional-programming - `fun x -> x` 是 OCaml 中唯一具有 'a -> ' a 类型的函数吗?

ocaml - 从函数构建序列

list - 适用于 2 个列表的 OCaml 代码。有没有更好的方法

list - 在 OCaml 中编写列表追加函数

types - Concoqtion (Coq + MetaOCaml) - 为什么放弃?

polymorphism - OCaml 中的状态单子(monad)

ocaml - 如何在 OCAML 中使用 List.Map 跳过一个术语?

list - 如何可靠地比较列表的整数或浮点值?

javascript - 如何使用 js_of_ocaml 添加 onclick 方法?

casting - OCaml:将 bool 转换/转换为 int