Can I inherit from the OCaml class selected at runtime?

So now I have two classes of the same type of class, for example

class foo : foo_type = object ... end class bar : foo_type = object ... end 

I would like to have a third class that inherits from foo or bar at runtime. For instance. (Pseudo-syntax)

 class baz (some_parent_class : foo_type) = object inherit some_parent_class ... end 

Is this possible in OCaml?

Use case: I use objects to build AST visitors, and I would like to be able to combine these visitors based on a set of runtime criteria so that they perform only one combined AST tour.

Edit: I think I found a way to create the desired class using first-class modules:

 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) 

However, it seems to twirl a bit to wrap a class in a module to make it โ€œfirst-classโ€. If there is an easier way, let me know.

+5
source share
3 answers

It doesn't contradict what Jeffrey said, but you can achieve this using first-class modules. Also, I'm not sure if you really need to create classes at runtime, maybe creating an object will be enough. If what you want is a different behavior, then that will be enough.

+3
source

This is just a cleaner implementation of what you already suggested, but I would do it like this:

 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 Mc method y = self#x + 2 end 
+4
source

OCaml has a static type system. You cannot do anything at run time, which will affect the type of something. Inheritance affects the types of things, so this cannot happen at run time.

(Your code also confuses types with values, which is understandable).

There is probably a way to get closer to what you want while maintaining the desired properties of static typing. What you really need may be more like a mix of functions, perhaps.

+2
source

Source: https://habr.com/ru/post/1213745/


All Articles