Browse thread
Coercion of arrays of objects (and some other containers)
-
Martin Jambon
- Olivier Andrieu
- Jacques Garrigue
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
| Date: | -- (:) |
| From: | Jacques Garrigue <garrigue@m...> |
| Subject: | Re: [Caml-list] Coercion of arrays of objects (and some other containers) |
From: Martin Jambon <martin_jambon@emailuser.net>
> 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
Suppose that it worked.
Then you could have this scenario.
let arr = [|obj|];;
let arr' = (arr :> <a:unit> array);;
arr'.(0) <- object method a = () end;;
arr.(0)#b;;
Segmentation fault.
Such subtyping is allowed in Java, but this is an unsafe part of the
type system, which requires time-consuming runtime checks.
> 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?
If you don't need to add objects to this hash table, this is possible
with the following approach:
class ['a,+'b] table tbl =
object
val tbl : ('a,'b) Hashtbl.t = tbl
method find = Hashtbl.find tbl
method find_all = Hashtbl.find_all tbl
method mem = Hashtbl.mem tbl
end
(* class ['a, 'b] table :
('a, 'b) Hashtbl.t ->
object
val tbl : ('a, 'b) Hashtbl.t
method find : 'a -> 'b
method find_all : 'a -> 'b list
method mem : 'a -> bool
end *)
let coerce tbl = (tbl : ('a,<a:int;b:int>) table :> ('a,<a:int>) table)
See that 'b appears only in covariant positions, allowing its
subtyping.
Jacques Garrigue