Type Parameters are Completely Unnecessary

Brendan Eich brendan at mozilla.org
Wed Mar 5 10:56:18 PST 2008


On Mar 5, 2008, at 12:27 AM, Darryl wrote:

> Perhaps you could provide an example of a situation in
> which this sort of type parameter on collections is
> beneficial. I can't picture a situation in which,
> given what you've said, this could be at all useful,
> and that might be why I fail to see the point of doing
> it this way.

Sure. Here's ES4 Map as proposed:

__ES4__ dynamic class Map.<K,V>
{
     public function Map(equals:   function = (function(a,b) a === b),
                         hashcode: function = intrinsic::hashcode) …

     static meta function invoke(object: Object): Map.<EnumerableId,*> …
     static public const length = 2;

     intrinsic function size() : uint …
     intrinsic function get(key: K, notfound: (V|undefined) 
=undefined) : (V|undefined) …
     intrinsic function put(key: K, value: V, notfound: (V|undefined) 
=undefined) : (V|undefined) …
     intrinsic function has(key:K) : boolean …
     intrinsic function remove(key:K) : boolean …
     intrinsic function clear() : void …

     iterator function get(deep: boolean = false) :  
iterator::IteratorType.<K> …
     iterator function getKeys(deep: boolean = false) :  
iterator::IteratorType.<K> …
     iterator function getValues(deep: boolean = false) :  
iterator::IteratorType.<V> …
     iterator function getItems(deep: boolean = false) :  
iterator::IteratorType.<[K,V]> …

     private const equals   : function = …
     private const hashcode : function = …
     private var population : uint = …
}

By convention the type parameter names are short, all-caps. A couple  
of points:

* The type parameter list .<K,V> makes it clear that class Map is  
generic, you have to intantiate it with type arguments before you can  
call its constructor with equals and hashcode function arguments.

* The type parameters and annotations that use them make evaluation  
in either standard or strict mode straightforward for users to reason  
about. Readers can see that K means the same thing everywhere, they  
do not have to read verbose, runtime-type-checking code in each method.

How would you rewrite this class to avoid the syntax you don't like?  
You don't have to preserve constant type terms. Use ES3 if you like.

/be


More information about the Es4-discuss mailing list