views:

514

answers:

4

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

+1  A: 

There's a discussion of "Matching Objects With Patterns" on Lambda the Ultimate (the paper uses Scala as the language, so won't answer your question). A more relevant Ocaml mailing list thread indicates that there's 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) matching

Someone did write an extension that allows down/up-casting Ocaml objects.

wrang-wrang
I'm having a hard time getting this to work. I've done pattern matching for values within one type but not across several.
Rosarch
There's a difference between objects and algebraic types. Most people seem to prefer to avoid Ocaml's objects and use functors + algebraic types for genericity.
wrang-wrang
+4  A: 

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

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

let foo x = x#bar
newacct
A: 

In short, you have to encode your own RTTI mechanism. OCaml provides no RTTI or up/down casting (the latter in part because inheritance and subtyping are orthogonal in OCaml rather than unified as in Java).

You could do something with strings or polymorphic variants to encode type information in your classes and objects. I believe that LablGTK does some of this, and provides a utility library to support object tagging and up/down casting.

Michael E
A: 

Somewhat out-of-topic, but the OPA language (which draws heavily from some aspects of OCaml), allows the equivalent of pattern-matching on objects. So it's quite feasible.

Yoric