Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] a design problem requiring downcasting? (long)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Alessandro Baretta <alex@b...>
Subject: Re: [Caml-list] a design problem requiring downcasting? (long)

Michael Vanier wrote:

 > 1) multiple dispatch polymorphism (dispatching on the 
types of both obj1
 >    and obj2).  This is the most elegant approach, but 
almost no languages
 >    support this (I think because it's very hard to 
implement efficiently).

Oh, so what you really need is RTTI, not downcasting, 
really. I cannot help you here. I think you need method 
overloading for this one, and I doubt you'll get it soon in 

 > 2) a way to do a typecase on obj2 to determine which 
subclass of sim_object
 >    it is, so I can do the right thing.

Here's a quick implementation of RTTI in O'Caml which you
can use for your runtime switches

module Sim : sig
   class type sim_obj_t = object ... end
   val new_foo_sim : unit -> [> `Foo_sim of sim_obj_t ]
   val new_bar_sim : unit -> [> `Bar_sim of sim_obj_t ]
end = struct

   class type sim_obj_t = object end

   class virtual sim_obj : sim_obj_t =
   object (self)

   class foo_sim : sim_obj_t =
   object (self)
     inherit sim_obj
   let new_foo_sim () = `Foo_sim (new foo_sim)

   class bar_sim : sim_obj_t =
   object (self)
     inherit sim_obj
   let new_bar_sim () = `Bar_sim (new bar_sim)


let rtti_algorithm = function
| `Foo_sim x -> "Let's foo!"
| `Bar_sim x -> "Let's bar!"
| _ -> raise Not_found

You can place the RTTI dependent code within a method, thus 
obtaining something like double-dispatch polymorphism. Of 
course, you must explicitly code all cases you want your 
code to handle within a single pattern-matching in each 
class implementing your base class type; however, you get 
the plus of not having to keep an explicit roster of all 
your class type flags in one place.

You can also take advantage of the type checker by removing 
the catch-all underscore and letting the compiler signal 
what cases are missing from the pattern matching for it to 
be complete.

I'm curious about this, so I would be glad if you let me 
know what you end up doing.


To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: