caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: Ashish Agarwal <agarwal1975@gmail.com>
To: Caml List <caml-list@inria.fr>
Subject: [Caml-list] deep coercion does not work for some stdlib types
Date: Fri, 1 Feb 2013 15:27:40 -0500	[thread overview]
Message-ID: <CAMu2m2KBig1m=nvG_hf_axVJj64bnrKJFGieaxduCW3z5-VyEQ@mail.gmail.com> (raw)

[-- Attachment #1: Type: text/plain, Size: 1022 bytes --]

Section 7.9.2 of the manual gives this example:
http://caml.inria.fr/pub/docs/manual-ocaml-400/manual021.html#toc76

# 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?

[-- Attachment #2: Type: text/html, Size: 1666 bytes --]

             reply	other threads:[~2013-02-01 20:28 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2013-02-01 20:27 Ashish Agarwal [this message]
2013-02-01 20:39 ` Lukasz Stafiniak
2013-02-01 20:44   ` Lukasz Stafiniak
2013-02-01 23:37   ` Ashish Agarwal
2013-02-02  1:33   ` Jacques Garrigue

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to='CAMu2m2KBig1m=nvG_hf_axVJj64bnrKJFGieaxduCW3z5-VyEQ@mail.gmail.com' \
    --to=agarwal1975@gmail.com \
    --cc=caml-list@inria.fr \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).