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] Question: 'instanceof'-like like primitive in OCaml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-04-05 (18:15)
From: Brian Rogoff <bpr@b...>
Subject: Re: [Caml-list] Question: 'instanceof'-like like primitive in OCaml
On Wed, 4 Apr 2001, Nobuyuki Tomizawa wrote:
> Dear all,
> I'm a novice OCaml programmer and have a question about heterogeneous
> list and "downward cast".

There are no downcasts in the OCaml object system. Someone posted a patch
which would allow it but if you want to use standard OCaml you have to
write code without it. It is bad OO style anyways, right? 

> and what I want to do are:
>      * make the list which typed as "base list".
>      * call `derived2#specific' method if the element in the list is
>      an instance of 'derived2'.
> But, OCaml seems not to have Java's `instanceof'-like primitive and/or
> downward-cast primitive.
> My solution is to use variant type for the list and identify the class
> using pattern matching:
>     type tag = Derived2 of d2 | DontCare of b;;
>     let l = [ Derived2(new d2); DontCare(new d1 :> b)] in ...;;
> But I feel this solution is awkward because we have to define variant
> type for each classes I want to treat them as specific.
> Could you please tell me more 'smart' answer or another way in OCaml
> style?

Actually, what you have isn't too bad, and you have to use variants to
get the capability that you want. I do  something like the following to
get leaf and hier node object classes which can go on the same structure, 
maybe this is helpful to you. 

type ('a, 'b) node = Leaf_node of 'a | Hier_node of 'b
type ('a,'b) instance =
    CellRef of (Atom.t * ('a, 'b) node * placement)
  | CellArrayRef of (Atom.t * ('a, 'b) node * placement * colrow * ipoint * ipoint)

class virtual leaf_intf  =
    method virtual full_view : (leaf_intf, hier_intf) node
and virtual hier_intf =
    inherit leaf_intf
    method virtual leaf_view : (leaf_intf, hier_intf) node
    method virtual insts : (leaf_intf, hier_intf) instance list

where instances will look like 

class some_leaf  =
  object (self)
    inherit leaf_intf
    method full_view = Leaf_node (self :> leaf_intf)

class some_hier = 
  object (self)
    inherit hier_intf
    method full_view = Hier_node (self :> hier_intf)
    method leaf_view = Leaf_node (self :> leaf_intf)

In all honesty though, when you need to do this kind of thing a lot you
should consider writing the code using algebraic data types rather than 
classes. I think that people used to a mostly OO language should avoid the 
OO features until they are comfortable with the classic ML way. 
-- Brian

To unsubscribe, mail  Archives: