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] 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: 2004-04-01 (04:00)
From: briand@a...
Subject: Re: [Caml-list] examples of heterogenous collections (containers ?)
>>>>> "skaller" == skaller  <> writes:

  skaller> You are thinking about this problem *backwards*! :)

Well that's why it's giving me so much trouble. :-)

  skaller> The cast will always work if the object has a method named
  skaller> 'f' which when invoked with no arguments returns unit.
  skaller> Obviously, because Ocaml is wonderful, your cast will fail
  skaller> on objects without a suitable 'f' method.

I LIKE IT.  No inheritance required.  Objects which have the same
method with the same signature work "automagically".

  skaller> The solution is to use a factory function in a single
  skaller> module, and return an abstraction of the class type you
  skaller> wish to deal with.

I'm not sure I followed that, can you expand ?

For future readers of the list here and appropriate example.  It turns
out I was silly and never even bothered to look in the _manual_ of all
places.  I looked everywhere else.  This is covered in the section
called "Using Coercions", go figure.

Anyway, enough blather, here's the example :

class elt = object
  method f x = 2 * x

class elt_A = object
  method f x = 3 *x
  method g x = 3. *. x

let the_list = [ new elt; new elt ; ((new elt_A) :> elt) ]

List.iter (fun x -> print_int (x#f 2);) the_list

It does the right thing.  Here is a nice example to show type safety.
Re-define elt_A as:

class elt_A = object
  method f x = 3. *. x
  method g x = 3. *. x

And get the error :

This expression cannot be coerced to type elt = < f : int -> int >;
it has type elt_A = < f : float -> float; g : float -> float >
but is here used with type #elt as 'a = < f : int -> int; .. >

Thanks to all who answered.


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