Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] examples of heterogenous collections (containers ?)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Martin Jambon <martin_jambon@e...>
Subject: Re: [Caml-list] examples of heterogenous collections (containers ?)
On Tue, 30 Mar 2004, Matt Gushee wrote:

> On Tue, Mar 30, 2004 at 08:55:36PM -0800, briand@aracnet.com wrote:
> >
> > I'm embarking on that most typical of ewexamples, the heterogenous list.
> >
> > So I have objects:
> >
> > base_class
> >   virtual method
> >
> > derived_class_A
> >   inherit base_class
> >
> > derived_class_B
> >   inherit base_class
> >
> > ...
> >
> > And I would like to collect instances of derived_class_B,
> > derived_class_B etc.. into a data structure.
> >
> > The obvious example is that I'd like to collect the objects into a
> > list and do something like :
> >
> > List.iter
> >   (f obj ->
> >     obj#method)
> >   list_of_objs
>
> This will work if all the classes have identical signatures. Of course,
> that's not the case for most non-trivial examples.
>
> > or is (obj :> base_class)#method ?
>
> Probably not. First of all, you will need to cast the objects at the
> point where you put them into a list together ... thus, at the point
> where you do the method call, the cast has already been done.

And to keep trace of the original object, we would use polymorphic
variants:

class virtual ['a] base_class =
object
  method virtual variant : 'a
end

class ['a] derived_class_A =
object (self)
  inherit ['a] base_class
  method variant = `A self
end

and ['a] derived_class_B =
object (self)
  inherit ['a] base_class
  method variant = `B self
end

type variant = [ `A of variant derived_class_A
	       | `B of variant derived_class_B ]

let a = new derived_class_A
let b = new derived_class_B
let l = [ (a :> variant base_class);
	  (b :> variant base_class) ]
let list_of_variants = List.map (fun o -> o#variant) l


But maybe it is more convenient to not define a variant method, just
build a list of specialized objects:
  let list_of_variants = [ `A obj1; `B obj2; `C anything; ... ]

and then:
  let l = List.map (function `A o | `B o | `C o -> (o :> base_class))

(but here you loose the reference to the specialized version)


Martin

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners