Browse thread
[Caml-list] does class polymorphism need to be so complicated?
[
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: | Benjamin Geer <ben@s...> |
| Subject: | Re: [Caml-list] does class polymorphism need to be so complicated? |
brogoff@speakeasy.net wrote:
> The extension of Brian's code to rows with more than one field is obvious
> though, isn't it?
>
> type fbbq =
> <foo: int->int; bar: unit->string; baz: unit->bool;quux: unit->unit>
>
> class thing_processor =
> object
> method do_something (o : fbbq) =
> (* do something that calls all those methods *)
> method do_something_else (o : fbbq) =
> (* do something else that calls all those methods *)
> end
Unless I've missed something, this only works if none of the classes of
type fbbq have any additional methods. Here's an example that doesn't work:
type fbbq =
<foo: int->int; bar: string; baz: bool; quux: unit > ;;
class thing x_init =
object (self)
val mutable x = x_init
method foo y = x + y
method bar = string_of_int (self#foo 2)
method baz = (x = 1)
method quux = print_string (string_of_int x)
end;;
class extra_thing x_init =
object (self)
inherit thing x_init
method quuux = self#quux; self#quux
end;;
class thing_processor =
object
method process (obj : fbbq) =
obj#quux;
print_string (string_of_int (obj#foo 1));
print_string obj#bar;
print_string (string_of_bool obj#baz)
end ;;
let et = new extra_thing 1 ;;
let tp = new thing_processor ;;
tp#process et ;;
The call to 'process' produces the following error:
This expression has type
extra_thing =
< bar : string; baz : bool; foo : int -> int; quuux : unit; quux :
unit >
but is here used with type
fbbq = < bar : string; baz : bool; foo : int -> int; quux : unit >
Only the first object type has a method quuux
So this approach doesn't fit the requirement, which is to be able to use
a derived class anywhere its base class can be used.
Ben
-------------------
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