Section 7.9.2 of the manual gives this example:
# module N : sig
type t = private int
val of_int: int -> t
val to_int: t -> int
end
= struct
type t = int
let of_int n = assert (n >= 0); n
let to_int n = n
end;;
module N : sig type t = private int val of_int : int -> t val to_int : t -> int end
Deep coercion to a list of integers works as expected:
# let l = List.map N.of_int [1;2;3];;
val l : N.t list = [1; 2; 3]
# (l :> int list);;
- : int list = [1; 2; 3]
But for arrays it doesn't work:
# let a = Array.of_list l;;
val a : N.t array = [|1; 2; 3|]
# (a :> int array);;
Error: Type N.t array is not a subtype of int array
Is this because the array type does not have a variance annotation? If so, why doesn't it?
I can get around this by mapping over the elements:
# Array.map (fun (x : N.t) -> (x :> int)) a;;
But am I right that coercions have no run-time cost, as where the mapping will?