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 (17:38)
From: Nobuyuki Tomizawa <tomizawa@c...>
Subject: [Caml-list] Question: 'instanceof'-like like primitive in OCaml
Dear all,

I'm a novice OCaml programmer and have a question about heterogeneous
list and "downward cast".

Here is a pseudo Java code (I have):

     class base {
     	void common() {...};

     class derived1 extends base {

     class derived2 extends base {
	void specific() {..};

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

Thanks in advance.

-- Nobuyuki
To unsubscribe, mail  Archives: