Python and generic programming

Steven Bethard steven.bethard at gmail.com
Tue Oct 26 18:25:23 EDT 2004


Oliver Fromme <olli <at> haluter.fromme.com> writes:

> 
> Steven Bethard <steven.bethard <at> gmail.com> wrote:
>  > I'm not clear from your description (maybe you could show an example or 
>  > two?) but I gather you could either be talking about union typing, where at 
>  > compile time a variable is declared as, e.g. (list OR int), or parametric 
>  > polymorphism, where a variable's type is parameterized by another type, 
>  > e.g. list<type>.  In either of these cases, I would typically still call it 
>  > static typing because the possible types are still resolved at compile 
>  > time.  (The first will be handled much like a C union, and the second will 
>  > typically be stored as a list of objects, with some run-time checking of 
>  > type inserted, as in Java 1.5.)
> 
> Neither.
[bigsnip]
> The type inferred for sort, 'a list -> 'a list, means that
> sort can actually apply to lists of any type, and returns a
> list of the same type.  The type 'a is a type variable, and
> stands for any given type.

This is called parametric polymorphism, and was the second of my suggested
interpretations of your statement.

In parametric polymorphism, a variable's type is parameterized by another type.
 In your example, the list type is parameterized by another type.  In fact,
OCaml's 'a list translates directly into Java's List<T>.  Since in Java, not all
types are comparable, a similar sort function would have parameter and return
types of List<T implements Comparable>.  Of course, Java lacks type inference,
so the programmer has to declare this type manually, but in either case, the
type is checked at compile time, and as you suggest, comparisons between
uncomparable types would be raised as a compile time error.  Such parametric
polymorphism exists only in statically typed languages because it depends on
type declarations (or inferences).

Steve




More information about the Python-list mailing list