Browse thread
[Caml-list] examples of heterogenous collections (containers ?)
-
briand@a...
-
Matt Gushee
-
briand@a...
-
skaller
- briand@a...
-
skaller
- Martin Jambon
-
briand@a...
-
Matt Gushee
[
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: | briand@a... |
| Subject: | Re: [Caml-list] examples of heterogenous collections (containers ?) |
>>>>> "skaller" == skaller <skaller@users.sourceforge.net> 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 end ;; class elt_A = object method f x = 3 *x method g x = 3. *. x end ;; 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 end 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. Brian ------------------- 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