Version française
Home     About     Download     Resources     Contact us    
Browse thread
Same label in different types, how do people solve this?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: John Max Skaller <skaller@o...>
Subject: Re: Same label in different types, how do people solve this?
Mattias Waldau wrote:
> 
> In Ocaml, you cannot have the same label in different types, see the example
> below where
> point_2d hides point_3d.
> 
> How do people normally code around this restriction? 

	Use distinct names :-)
The 'correct' solution is a bit messy: use modules.

> Also, I am a bit curious why it doesn't help to type explicitely, i.e. to
> write
> let x:point_3d={x=10.;y=20.;z=30.} ???

 	The RHS is typed without examining the type constraint on the LHS,
then the constraint is checked. As in:

	let f (x : int) : int = "Hello"

The type of f is first infered as 'a -> string, as if it had been
written

	let f x = "Hello"

then this type is unified with the declared type constraint. In your
example,
the type is infered to be point_2d, since you declared that second, and
the 
field name 'x' is associated with this type: the previous binding
of x to (a field of the) type point_2d is hidden.
 
For your example try:

module D3 = struct
 type point = {
     x:float;
     y:float;
     z:float;
   }
end
module D2 = struct
 type point = {
     x:float;
     y:float;
   }
end
;;

{D3.x=10.;D3.y=20.;D3.z=30.};;

The 'field names' escape out of the type like a C enumeration,
to allow type inference to deduce the type of a record literal.

-- 
John (Max) Skaller, mailto:skaller@maxtal.com.au
10/1 Toxteth Rd Glebe NSW 2037 Australia voice: 61-2-9660-0850
checkout Vyper http://Vyper.sourceforge.net
download Interscript http://Interscript.sourceforge.net