From: Michael Vanier <mvanier@cs.caltech.edu>
> 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
downcasting.
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)
end
class ['a] b x = object (self)
inherit ['a] a x
method set_x y = x <- y
method me : 'a = `Tb (self :> _ b)
end
# 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 caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners