Type parameters

P T Withington ptw at pobox.com
Wed Sep 6 11:15:04 PDT 2006

On 2006-09-06, at 10:24 EDT, Dave Herman wrote:

> In both cases, the implementation of the collection is type-correct  
> with no runtime down-casts. The difference is at the point of use,  
> though. The bounded parametric implementation allows clients to  
> write programs like this:
>     var ls : List.<Foo> = new List.<Foo>(...);
>     var x : Foo = ls.head();
> Whereas in the non-generic example, the client code looks like:
>     var ls : List = new List(...);
>     var x : Foo = cast Foo(ls.head());


>> least a bit of type inference, it's very difficult to have everything
>> being sound.
> I don't know what you mean; inference may be a handy tool, but it  
> isn't required for type soundness.

It seems to me that the compiler has to do a fair bit of inferencing  
to avoid runtime type-checks or casts in either case.  It has to  
infer the actual type of the expression `new List` and make sure it  
is a subtype the declared type of `ls`, it has to determine if that  
inferred type is sealed, so that it can choose the appropriate method  
that `ls.head` will actually bind to, and it has to determine the  
return type of that method and make sure it is a subtype of the  
declared type of `x`.

What the parametric case does for the compiler is that the programmer  
explicitly declares that the collection is going to have elements of  
a uniform type, which would be pretty difficult to infer.

A question I always like to ask is:  does this language construct  
make the programmer's job easier, or does it make the compiler- 
writer's job easier?  (Given the hope that there will be many more  
programs than compilers, I favor the former.)  Presumably the non- 
parametric case can also be written:

   var ls = new List(...);
   var x = ls.head();

which sure makes the programmer's job easier.

Does it make the compiler-writer's job harder?  I'm not sure.  The  
compiler can still infer the type of ls, figure out if it is sealed,  
and determine the return type of the applicable method.  But  
depending on how x is used later in the program, the compiler may  
actually not have to do any of this work, since it does not have to  
determine if the actual types of the rhs expressions match the  
declared types of the lhs, since there are none.  (I realize that  
work might be worthwhile to enable optimizations.)

More information about the Es4-discuss mailing list