Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Why can't I use val mover : < move : int -> unit; .. > list -> unit ?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2001-01-11 (17:39)
From: Sylvain BOULM'E <Sylvain.Boulme@l...>
Subject: Re: Why can't I use val mover : < move : int -> unit; .. > list -> unit ?
> I understand the principle that the compiler must be sure that everywhere I
> use the list, the elements will be of the right type. In this case each
> element must have the method move.
> However, it seems to me that in this case the compiler has already done the
> complex part, i.e. realizing that if all objects have a move-method, then
> everything is ok. So I don't see the point that I have to coerce explicitily
> when putting elements into the list.
Such a coercion is not always possible: forget the "unnecessary" methods has not always a meaning. For instance, let's have an example a bit more complex than yours :

In the context :

class pt = 
  object (_:'a) 
    method compare (x:'a) = true

class qt (i:int) = 
  object (s:'a)
    val mutable state = i
    method compare (x:'a) = x#get = s#get 
    method get = state 

let p = new pt and q1 = new qt 1 and q2 = new qt 2;;

(** test if x is comparable to all elements of l **)
(* val compare_iter : < compare : 'a -> bool; .. > list -> 'a -> bool *)
let compare_iter l x = List.fold_left (fun b y -> b && y#compare x) true l;; 

compare_iter [p;p] p;;
compare_iter [q1;q2] q1;;

Both these expressions below are not well-typed :
compare_iter [q1;q2] p;;
compare_iter [(q1:> pt);(q2:> pt)] p;;

Indeed, an object of type "qt" can not be coerced to an object of type "pt" because an object of type "qt" needs an object with a "get" method as argument for "compare". What is interesting here with ocaml polymorphism, is that you can however have a function as "compare_iter" which can both handle "lists of pt" and "lists of qt".

Hope this helps,