Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] functional objects
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Didier Remy <Didier.Remy@i...>
Subject: Re: [Caml-list] functional objects
> I mistakenly assumed, since the documentation does not explicitly say 
> that the inherit clause defines a constructor method named after the 
> superclass, that your examples would not compile.  Surprisingly, they 
> actually do in ocaml-3.06.  

I do not see how you inferred that they should not compiled form the
observation that:

   > the documentation not explicitly say the inherit clause defines a
   > constructor method named after the superclass

No, it does not say so and this is not true: the inherit
clause (1) [behaves as if one] copies the code from the parent class (2) can
be aliased to access methods of the superclass.  But the inherit clause does
not define a constructor method.  In the examples I gave, the constructor was
always explicitly defined.

> I have a suspicion, though, that the implementation makes a lot of 
> temporary copies in this process.  Is that so?

Yes, it does indeed. But do you really mind?  At least not in these toy
examples. Unless you are using this construction in a kind of systematic
way, and have long chain of inheritance, adding fields one-by-one, I am not
sure that one extra copies will create a significant lost in performance.

Anyway,  an alternative solution is to use the class constructor (of the
class you are defining) to build a new object from scratch. 
However, the definition must be split in two definitions because class
definitions are not recursive. 

    (* more general class *)
    class bar_ constr x y = object (self)
      inherit foo x  (* allow non zero argument to foo *)
      val y: int = y
      method g (a: int) (b:int) : bar = constr a b
    end;;
    
    (* close the recursion and specialize x to 0 *)
    class bar y = bar_ (let rec c x y = new bar_ c x y in c) 0 y;;

The two solutions are quite different: here (solution 2), a call to g
creates a fresh object of class "bar" from scratch (running the class
initializers if any) while in the previous solution it would only override
(functional update) an existing object.

The two solutions differ with respect to inheritance.  In a subclass gnu of
g, method g will have type gnu with solution 1 but will still have type bar
with solution 2.

There is no better solution, it just depends on the context.

        Didier Rémy
-------------------
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