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-08 (20:11)
From: Gerd Stolpmann <gerd@g...>
Subject: Re: [Caml-list] Question: 'instanceof'-like like primitive in OCaml
On Wed, 04 Apr 2001, Nobuyuki Tomizawa wrote:
>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.

I do not know the real reasons why the language designers refused to add these
constructs. However, I know from OO literature that they are often considered
as bad style, because they encourage programmers to mix object oriented
and procedural elements.

In Java you really need downcasts because Java lacks parametric polymorphism. 
For example, to use Java's stack class, you typically first cast your
elements to Object (which is done implicitly), and when you want to get your
elements back, you must downcast them to the class they previously had.

In O'Caml, the container types like stack have a type parameter (such as 
int Stack.t or string Stack.t) so the compiler already knows the type of the
elements; no downcasts are necessary as in Java.

>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

The traditional OO style is what you want:

class virtual base = object
  method common = ...

  method virtual specific : unit -> unit

class derived1 = object
  inherit base

  method specific() = ()

class derived2 = object
  inherit base

  method specific() = your action

Now, simply call x#specific for _all_ elements x of the list.

Gerd Stolpmann      Telefon: +49 6151 997705 (privat)
Viktoriastr. 100             
64293 Darmstadt     EMail:
To unsubscribe, mail  Archives: