Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] dynamic runtime cast in Ocaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2002-11-07 (08:11)
From: Jacques Garrigue <garrigue@k...>
Subject: Re: [Caml-list] dynamic runtime cast in Ocaml
From: Michael Vanier <>

> I understand some of the objections to downcasting, but what I'm really
> curious about is this: if the ocaml team really *wanted* to allow downcasts
> (raising an exception on failure just like dividing by zero does), would it
> be technically feasible?  By feasible I mean doable without nasty Obj.magic
> hacks (no offense to coca-ml, which is very clever).

Sure, it would be feasible.
And a bit more efficient than coca-ml, since we could put the class
identifier in a field rather than access it through a method.
But it would mean maintaining more runtime data for a feature of
disputed use.  From this point of view coca-ml is a possible approach:
it seems efficient enough, and you only use it when you really need

Note that coca-ml chooses to use Obj.magic, but there other ways to do
downcasting which do not require any magic. The weak hash-table
approach (see Weak_memo in Remy Vanicat's hweak library), or the
exception approach are examples of ways to do that.

And maybe someday we will see the light, and add a -with-rtti option
to Objective Caml. But do not hold your breath, as there is a strong
resistance to such an asymetric feature, which would work only on
non-parametric classes.

And this all the more as parametric classes are actually yet another
way to solve the problem:

class ['a] a (x : int) = object (self)
  val mutable x = x
  method x = x
  method me : 'a = `Ta (self :> _ a)

class ['a] b x = object (self)
  inherit ['a] a x
  method set_x y = x <- y
  method me : 'a = `Tb (self :> _ b)

# let some_b = new b 1;;
val some_b : (_[> `Ta of '_a a | `Tb of '_a b] as 'a) b = <obj>
# let hidden_b = (some_b :> _ a);;
val hidden_b : (_[> `Ta of '_a a | `Tb of '_a b] as 'a) a = <obj>
# match hidden_b#me with `Tb b -> b | _ -> assert false;;
- : (_[> `Ta of '_b a | `Tb of 'a] as 'b) b as 'a = <obj>

Ahem, types are ugly, but it works...

Jacques Garrigue
To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: