Version française
Home     About     Download     Resources     Contact us    
Browse thread
Coercion of arrays of objects (and some other containers)
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Olivier Andrieu <andrieu@i...>
Subject: Re: [Caml-list] Coercion of arrays of objects (and some other containers)
Salut Martin,

 > Martin Jambon [Tue, 12 Apr 2005]:
 > Here is my problem:
 > 
 > # let obj =
 > object
 >   method a = ()
 >   method b = ()
 > end;;
 >         val obj : < a : unit; b : unit > = <obj>
 > 
 > (* That is nice: *)
 > # ([ obj ] :> < a : unit > list);;
 > - : < a : unit > list = [<obj>]
 > 
 > (* But why doesn't it work with arrays? *)
 > # ([| obj |] :> < a : unit > array);;
 > Characters 1-10:
 >   ([| obj |] :> < a : unit > array);;
 >    ^^^^^^^^^
 > This expression cannot be coerced to type < a : unit > array; it has type
 >   < a : unit; b : unit > array
 > but is here used with type < a : unit > array
 > Only the first object type has a method b

It's a variance problem : a list is covariant so the coercion
works. But an array is invariant (because of the Array.set
operations).

Otherwise after coercion you would be able to do store in the array an
object without a `b' method, this object being also reachable through
the original array.

 > In practice I have this problem with a hash table of objects, and I
 > expected it to work since it works fine with lists of the same
 > type of objects...
 > Is there any workaround?

Maybe this :

  Array.map (fun o -> (o :> < a : unit >)) [| obj |] 

-- 
   Olivier