
Pascal and most other languages of the 70's are based on the idea that functions and procedures, and hence, operands have a unique type. Pascal is monomorphic.
Polymorphic functions are functions whose operands can have more than one type. For example:
For example, we can define listlen, a function that finds the length of a list in Haskell as follows:
module ListOps (listlen) where
{
listlen [] = 0;
listlen (x:xs) = 1 + listlen xs
}
This function should work no matter what type of element is stored in the list!
Ad hoc polymorphism occurs when an operator works, or appears to work, on several different types (which may not exhibit a common structure) and may behave in unrelated ways on each type. There is no conceptual restriction on ad hoc polymorphism.
For an example of ad hoc polymorphism, consider the following operations:
3 + 4 3.0 + 4 3 + 4.0 3.0 + 4.0
The apparent polymorphism can be explained as:
Most languages that are monomorphic have some features that are polymorphic:
Universally polymorphic functions generally work on an infinite number of types (all having a common structure).
Parametric polymorphism:
Consider again the definition of listlen from above. What type does Haskell infer for it?
:type listlen listlen :: Num a => [b] -> a
Thus len takes a list with elements of type b and returns a number. We call b a type variable since any valid type can be used.
Parametric polymorphism also appears in C++ templates, where you write the code once but instantiate different versions of it based on type parameters.
Inclusion polymorphism
An example of inclusion polymorphism is given by sets, bags, and tuples:
Since bag and tuple are children of set, they can all be referred to as a type of set. Inclusion polymorphism is the kind you find most often in object-oriented languages. For example, in Java all classes inherit from the java.lang.Object class. Thus, any code you write to work on the "Object" class works on any class without having to handle special cases. Also, any of the objects that you create in Java can be accessed through a reference of type "Object."
This diagram shows one way type systems
can be classified.-->

A postscript copy of the diagram is also available.

Last updated at 9:54 am on Friday, August 27, 2004.