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:07)
From: Didier Le Botlan <didier.le-botlan@p...>
Subject: Re: [Caml-list] Question: 'instanceof'-like like primitive in OCaml

Because of strong typing, heterogeneous lists are not allowed (which is
actually good).

As far as I understand, what you need is 
 - some kind of "instanceof"
 - some kind of dynamic cast (depending on the result of "instanceof").

You have many ways to get instanceof :

For example you can declare a virtual method "instanceOfSpecific : bool"
in base class, and each subclass must define it. 

Dynamic cast is not possible here because a base object cannot be seen
as a "derived2" object in general.
You can declare a method "specific" which raises an exception (default
behaviour) and which is overriden in class "derived2" to do what

Thus, if you incorrectly call "specific" method on a "derived1" object,
an exception is raised. This corresponds somehow to an incorrect dynamic
cast in Java.

Finally, here is a short example :

class virtual base =
  method common x = x+1
  method virtual isSpecific : bool
  (* 'specific' returns a string. failwith is polymorph, we must help
type checker. *)
  method specific = ((failwith "specific is not defined !!!") : string)

class derived1 =
  inherit base
  method isSpecific = false
class derived2 message =
  inherit base
  method isSpecific = true
  method specific = "Hello " ^ message

let example =
  print_endline "Starting...";
  let obj1 = new derived1
  and obj2 = new derived2 "World"
  and obj3 = new derived2 "Folks" in
  let list = [ obj1 ; obj2 ; obj3; obj2 ; obj1 ] in
  let apply_specific obj =
    if obj#isSpecific then print_endline obj#specific
    else print_endline "No Specific"
    List.iter apply_specific list

compile :
ocamlc -o exam

and try...

Nobuyuki Tomizawa wrote:

> 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.
To unsubscribe, mail  Archives: