Version française
Home     About     Download     Resources     Contact us    
Browse thread
Question about polymorphic variants
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Jacques Garrigue <garrigue@m...>
Subject: Re: [Caml-list] Question about polymorphic variants
From: Xavier Clerc <xcforum@free.fr>

> > An example close to the above one would be:
> >
> > # List.map (fun (x,y) -> x+1);;
> > - : (int * '_a) list -> int list = <fun>
> >
> > Now you might wonder why '_a cannot be polymorphic in the above
> > example. That is, could there really be a definition of List.map such
> > that the polymorphic type would be dangerous (causing a segmentation
> > fault for instance.)
> 
> This is indeed the question I was asking to myself ...
> 
> 
> > The answer is yes, with a counter-example using
> > the difference in representation between normal arrays and float
> > arrays.
> 
> In this counter-example, it is not clear to me whether the possible  
> problem is type-related or runtime-related. I mean, would this  
> counter-example still hold if arrays were both boxed or both unboxed ?

No, the difference in representation is essential here.

But at the type level, this problem can be expressed a bit
differently: whether it is safe to add a "top" to the type system,
allowing any type to be coerced to it. While some languages might
allow that, there is no fundamental reason it should be so (an this is
indeed not the case in ocaml.)
If we cannot assume the existence of such a type, then we cannot prove
that polymorphism in this case would be safe.

Note that the property used by the relaxed value restriction, that
one can always add safely a "bottom" to the type system, is much more
reasonable, as it's only assumption is that the representation of
values depend only on (typed) values, not on types alone. This is
valid in ocaml, but some other language might still break it.
> 
> > Actually, since this counter-example wouldn't apply to the above case
> > of polymorphic variants, this would probably be safe to leave the
> > polymorphic variant type as polymorphic...
> 
> Does this mean that inferring "[< `Off | `On] list -> int list" would  
> be perfectly safe in the example above ?
> (by saying so, I am not pleading for any compiler change, I am just  
> trying to organize my thoughts)

I believe so, but I don't have a proof ready for that.
One way to do it would be to prove that any instance of [< `Off | `On]
is a subtype of [ `Off | `On ], which sounds trivial in this case.
So I would say this should apply to both [< ... ] types (closed
polymorphic variants, including the [< ... > ...] case) and <...; ..>
types (extensible object types.) But not to [> ...] types (open
polymorphic variants.)

Jacques Garrigue