Hi,

Consider functions foobar1 and foobar2:


type 'a t = {id: int; x: 'a}

let foobar1: 'a -> 'a t =
        fun x -> {id = 0; x}

let foobar2: 'a -> 'a t =
        let ctr = ref 0 in
        fun x -> incr ctr; {id = !ctr; x}



I would expect them to have the same type, because foobar2's
use of a reference cell is kept private.  However, they don't.
In fact, foobar2 is not really polymorphic:


type 'a t = { id : int; x : 'a; }
val foobar1 : 'a -> 'a t
val foobar2 : '_a -> '_a t


It's easy to get around this issue by putting the reference cell
outside of foobar2.  Function foobar3 does just this, and behaves
as expected:


let next =
        let ctr = ref 0 in
        fun () -> incr ctr; !ctr

let foobar3: 'a -> 'a t =
        fun x -> {id = next (); x}



Could someone point me to a good explanation of what's going on?
(I have the feeling I've read about this restriction before.)

Best regards,
Dario Teixeira



-- 
Caml-list mailing list.  Subscription management and archives:
https://sympa-roc.inria.fr/wws/info/caml-list
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners
Bug reports: http://caml.inria.fr/bin/caml-bugs

Reply via email to