[
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: | Martin Jambon <martin.jambon@e...> |
| Subject: | Classes and polymorphism (Re: [Caml-list] Re: Why can't I call a function over a subclass?) |
On Fri, 5 Oct 2007, Luca de Alfaro wrote: > I am not so used to ":>"... looking at the example I posted, would you be > able to tell me how to make it type-check by adding ":>"? This would be > very much appreciated... Ah, sorry, I missed your second problem, which was: (next time please change the subject line and cc the list) class p (x: int) = object method plus1 : int = x + 1 end class p2 (x: int) = object inherit p x method plus2 : int = x + 2 end class r = object (self) val mutable l = [] method make_el x = new p x method add (x: int) : unit = l <- (self#make_el x) :: l method length : int = List.length l method total : int = List.fold_left (fun t el -> t + el#plus1) 0 l end class r2 = object inherit r method make_el x = new p2 x method total2 : int = List.fold_left (fun t el -> t + el#plus2) 0 l end What you're trying to do usually ends up being a nightmare: l would have to be polymorphic. Keeping classes polymorphic is not something practical. If you inherit an object value such as l, basically it will have one fixed type, and that's all. I find the following guidelines convenient: Define class types independently from class implementations when you know that you will have several classes of the same type. Only use monomorphic methods and values. You may inherit a class from another, and you don't need polymorphic classes for this. You never have to use inheritance. You don't have to use classes, immediate objects are often sufficient (object ... end). You can inherit and override methods, which is convenient when only a small subset of methods differ between two classes. That's when your classes are like an evolutionary tree of species. Don't bother when you have only 2 or 3 classes. Martin -- http://martin.jambon.free.fr