OCaml: type of object scan

If I have an object, how can I determine its type? (Is there an OCaml equivalent for the Java instanceof operator?)

+7
object instanceof ocaml typechecking
source share
4 answers

OCaml has structural typing for objects, and not named typing, as in Java. Thus, the type of an object is mainly determined (and determined only) by its methods. Objects in OCaml can be created directly without going through something like a class.

You can write functions that require that the objects of its argument have certain methods (and that these methods have certain types); for example, the following method takes an argument, which is any object with the bar method:

 let foo x = x#bar 
+7
source share

It discusses "Matching Objects with Templates" on Lambda the Ultimate (the document uses Scala as a language, so it won’t answer your question). The more relevant Ocaml mailing flow indicates that there is no RTTI / safe-downcasting for objects.

For algebraic (non-object) types, you obviously have:

 match expr with Type1 x -> x Type2 (x,y) -> y 

called (pattern)

Someone wrote an extension that allows you to add / remove Ocaml objects.

+4
source share

In short, you must encode your own RTTI engine. OCaml does not provide RTTI or up / down additions (the latter in part because inheritance and subtyping are orthogonal in OCaml and not unified like in Java).

You can do something with strings or polymorphic options to encode type information in your classes and objects. I believe LablGTK performs some of these functions and provides a utility library for supporting object tags and up / down quotes.

+1
source share

Somewhat because of the topic, but the OPA language (which relies heavily on some aspects of OCaml) allows the equivalent of a template to update objects. So this is quite feasible.

0
source share

All Articles