Version française
Home     About     Download     Resources     Contact us    
Browse thread
Polymorphic method and polymorphic type
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] Polymorphic method and polymorphic type
From: SerP <serp@stork.ru>
> Simple example. All functions are fake.
> 
> class getter = object method add_some p = p+1 end;;
> type 'a get_mode = [ `Read | `Watch of (#getter as 'a)];;
> let string_of_get_mode (gm: 'a get_mode) = match gm with `Read -> "Read" 
> | `Watch g -> let i = g#add_some 1 in ("Watch "^ (string_of_int i));;
> class c = object method pgm : 'a. ('a get_mode) -> string = 
> string_of_get_mode end;;
> --------------
> This expression has type 'a. (#getter as 'a) get_mode -> string
> but is here used with type 'b. (#getter as 'b) get_mode -> string
> Type #getter as 'c = < add_some : int -> int; .. >
> is not compatible with type 'c
> 
> ====================
> Please help. Is it my error? how should we do that the right way?

Unfortunately, explicitly polymorphic type variables inside
constrained type parameters are not allowed. This is due to the way
type expansion is done inside the type checker...
It should be possible to solve it, but I'm afraid lots of places would
have to be modified to provide comprehensive support.

Currently, the way to do it is to avoid constrained type parameters.

type 'a get_mode = [ `Read | `Watch of 'a];;
let string_of_get_mode (gm: #getter get_mode) =
   match gm with `Read -> "Read" 
  | `Watch g -> let i = g#add_some 1 in ("Watch "^ (string_of_int i));;
class c = object
 method pgm : 'a. (#getter as 'a) get_mode -> string = string_of_get_mode
end;;

This should not be too difficult usually. However, there is no
workaround if the type with the constraint is abstract.

Jacques Garrigue