Browse thread
[Caml-list] Question: 'instanceof'-like like primitive in OCaml
-
Nobuyuki Tomizawa
- Brian Rogoff
- Didier Le Botlan
- Gerd Stolpmann
[
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: | Didier Le Botlan <didier.le-botlan@p...> |
| Subject: | Re: [Caml-list] Question: 'instanceof'-like like primitive in OCaml |
Hello,
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
expected.
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 =
object
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)
end
class derived1 =
object
inherit base
method isSpecific = false
end
class derived2 message =
object
inherit base
method isSpecific = true
method specific = "Hello " ^ message
end
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"
in
List.iter apply_specific list
compile :
ocamlc -o exam exam.ml
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 caml-list-request@inria.fr. Archives: http://caml.inria.fr