CS 334
Programming Languages
Spring 2000

Lecture 15


Polymorphism

Implicit Polymorphism

Discussed last time.

Explicit Polymorphism

Clu, Ada, Eiffel, Modula-3, C++

No type inference. If have polymorphic function, must explicitly pass type parameter.

E.g.,

   fun map t u (f: t -> u) (l: t list): u list

Apply it:

   map string int length ["a","help","Willy"] = [1,4,5]

Write type as

   forall t. forall u. (t -> u) -> (t list) -> u list

Makes clear that t, u are type variables.

Can understand implicit polymorphic terms as abbreviations for explicit polymorphic terms. Compare with type of map in ML, above.

Explicit polymorphic terms more expressive!

Restrictions on polymorphism for ML.

Polymorphic functions can be defined at top-level or in let clauses, but polymorphic function expressions cannot be used as arguments of functions.

E.g.,

    let 
       fun id x = x 
    in 
       (id "ab", id 17) 
    end;
is fine, but can't write
    let 
       fun test g = (g [], g "ab")
    in 
       test (fn x => x) 
    end;
In fact, can't even write:
    fun test2 f = (f [], f 17);
Gets confused since f is used with two different typings:

'a list -> 'b, int -> 'c and can't unify 'a list and int.

No problem writing this in explicit polymorphic language:

    let 
       fun test  (g: forall t.t -> t): (int list, string) = 
                                        (g (int list) [], g string "ab")
    in 
       test (Fn t => fn (x:t) => x) 
    end;

Write f: forall t. T, if f takes a type parameter U and returns a value of type T[U/t].
Use Fn t => (rather than fn x =>) to indicate the parameter is a type.

Thus "id", defined by:

    fun id t (x:t) = x

A polymorphic function is one which takes a type parameter, which specializes it into a function of particular type. I.e., id T is function of type T -> T.

Think of "id" as representing a class of functions, each of which has uniform (parameterized) type.

Subtypes

Lecture material on subtypes can be found in pdf format (preferable for reading on-line) or postscript format (preferable for printing on a post-script printer). This material comprises Chapter 6 of the forthcoming book, Foundations of Object-Oriented Languages: Types and Semantics, by Kim Bruce (©2000 by Kim Bruce). The relevant material for this lecture is included in sections 6.1 and 6.4.


Back to:
  • CS 334 home page
  • Kim Bruce's home page
  • CS Department home page
  • kim@cs.williams.edu