English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
Type system infering 'a and '_a
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2006-09-13 (16:10)
From: Tom <tom.primozic@g...>
Subject: Type system infering 'a and '_a
I was playing a bit with Ocaml type system the other day...

  type 'a t1 = Empty1 | Full1 of 'a

  # let a1 = Empty1;;
  val a1 : 'a t1 = Empty1


  type 'a t2 = Empty2 of 'a option ref | Full2 of 'a

  # let a2 = Empty2 (ref None);;
  val a2 : '_a t2 = Empty2 {contents = None}

The type system won't infer a2 as being polymorphic, as it is mutable.

  type 'a t3 = Empty3 of string | Full3 of 'a

  # let a3 = Empty3 "foo";;
  val a3 : 'a t3 = Empty3 "foo"

Even thou a3 is mutable, mutating it can't bind 'a, so a3 is polymorphic.

  type ('a, 'b) t4 = Empty4 of 'a option ref | Full4 of 'a * 'b

  # let a4 = Empty4 (ref None);;
  val a4 : ('_a, 'b) t4 = Empty4 {contents = None}

As only 'a is "contained" in a mutable type, a4 is polymorphic only in 'b.

But now...

  type ('a, 'b) t5 =
      Empty_a5 of 'a option ref
    | Empty_b5 of 'b option ref
    | Full5 of 'a * 'b

  # let a5 = Empty_a5 (ref None);;
  val a5 : ('_a, '_b) t5 = Empty_a5 {contents = None}

Stupid. Value a5 should be polymorphic in 'b!

(And, with a bit of hacking:

  type 'a t1 = Empty1 | Full1 of 'a

  # let b1 = Full1 (Obj.magic 0);;
  val b1 : 'a t1 = Full1 <poly>


  type ('a, 'b) t4 = Empty4 of 'a option ref | Full4 of 'a * 'b

  # let b4 = Full4 (Obj.magic 0, Obj.magic 0);;
  val b4 : ('_a, 'b) t4 = Full4 (<poly>, <poly>)



So we see that "mutability" of each type variable is defined for the whole
type, not for the individual value constructors only. Is there a theoretical
reason (of course, one reason is probably an easier implementation)?

- Tom