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

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From:
Subject: Re: [Caml-list] Polymorphic graph widget problem
Hi, Richard

 Richard Jones [Friday 29 August 2003] :
 > As part of a project I'm doing at the moment, I've written a Gtk graph
 > widget using lablgtk. The graph currently plots ints, so the type
 > looks something like this:
 > 
 > class chart :
 >   ?width:int ->
 >   ?height:int ->
 >   ?packing:(GObj.widget -> unit) ->
 >   ?show:bool ->
 >   int array ->  (* the data being plotted *)
 >   object
 >     method repaint : Gdk.Rectangle.t option -> unit
 >   end
 > 
 > All fine, but now I'd like to generalise this so it can plot floating
 > point values as well as int, thus:
 > 
 > class ['a] chart :
 >   ?width:int ->
 >   ?height:int ->
 >   ?packing:(GObj.widget -> unit) ->
 >   ?show:bool ->
 >   'a array ->  (* the data being plotted *)
 >   object
 >     method repaint : Gdk.Rectangle.t option -> unit
 >   end

first, you do not need to parametrize your `chart' class if the type
variable doesn't appear in a method signature. I.e. you can do :

  class chart : 'a array -> object method repaint : ... end

or even :

  class chart : 'a array -> 
    object val data : 'a array method repaint : ... end

 > The problem with this is that at various places in the implementation
 > we need to break the polymorphism. eg. To plot Y labels we call
 > 'string_of_int', and to work out the height of the Y axis we do some
 > sums on the values using the (+) operator.

Here's one solution :

class virtual chart ?width ?height ?packing ?show (data : 'a array) =
  object (self)
    method private virtual sum : 'a array -> 'a
    method private virtual to_string : 'a -> string
    method repaint =
      (* code using self#to_string and self#sum *)
  end

class type chart_t = object method repaint : Gdk.Rectangle.t option -> unit end

class int_chart ?w ?h ?p ?s data : chart_t =
  object
    inherit chart ?w ?h ?p ?s data
    method private to_string = string_of_int
    method private sum a = Array.fold_left (+) 0 a
  end

class float_chart ?w ?h ?p ?s data : chart_t =
  object
    inherit chart ?w ?h ?p ?s data
    method private to_string = string_of_float
    method private sum a = Array.fold_left (+.) 0. a
  end

-- 
   Olivier

-------------------
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