Browse thread
[Caml-list] a design problem requiring downcasting? (long)
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | brogoff@s... |
| Subject: | Re: [Caml-list] a design problem requiring downcasting? (long) |
On Thu, 26 Sep 2002, Michael Vanier wrote:
> I've run into a design problem that I think requires downcasting, and I
> wanted to see if anyone on the list has any ideas about an alternative
> approach, since AFAIK downcasting is impossible in the current ocaml object
> system (at least without nasty Obj.magic hacks). I'll try to simplify the
> problem as much as possible, but this is still pretty long.
I'm not so sure about your specific problem, but when I've wanted my class
hierarchy to behave more like a sum type I've simply grafted a sum type over the
set of class types (or virtual classes). Here's a sketch for a composite
type ('a, 'b) node = Leaf_node of 'a | Hier_node of 'b
and ('a, 'b) instance =
CellRef of Atom.t * ('a, 'b) node * Geometry.placement
| CellArrayRef of
Atom.t * ('a, 'b) node * Geometry.placement * Gdsii.colrow * ipoint * ipoint
class virtual leaf_intf =
object
method virtual full_view : (leaf_intf, hier_intf) node
(* ... etc... *)
end
and virtual hier_intf =
object
inherit leaf_intf
method virtual leaf_view : (leaf_intf, hier_intf) node
method virtual insts : (leaf_intf, hier_intf) instance list
end
let as_leaf : (leaf_intf,hier_intf) node -> leaf_intf = function
Leaf_node(l) -> (l :> leaf_intf)
| Hier_node(h) -> (h :> leaf_intf)
let as_hier : (leaf_intf,hier_intf) node -> hier_intf = function
(* ...etc... *)
Obviously, this only works well if you have a fairly small number of
"abstract base classes", since each one is a type parameter. You don't even need
to use parametric polymorphism, and you could just declare a type specific to
this class hierarchy; take a look at
http://cristal.inria.fr/~remy/cours/appsem/ocaml049.html#toc22
where Didier Remy gives an example using variants and projection functions.
Also, the weak library mentioned elsewhere looks promising.
As I get older and lazier, I wonder more if a lot of the OO approaches are
really easier to grasp. A lot of people are going right for the O before going
through Caml, and that seems wrong.
-- Brian
-------------------
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