Revision as of 16:20, 7 May 2012 by Benmachine
A value is polymorphic if, depending on the context where it's used, it can take on more than one type.
There are different kinds of polymorphism.
- Parametric polymorphism; mostly found in functional languages
- Ad-hoc polymorphism or overloading
- Inclusion polymorphism; mostly found in object oriented languages
The type of
foldr :: (a -> b -> b) -> b -> [a] -> b
involves unrestricted type variables, so it is a parametrically polymorphic function. When actually used, it may take on any of a variety of types, for example:
:: (Char -> Int -> Int) -> Int -> String -> Int -- a = Char, b = Int (note String = [Char]) :: (String -> String -> String) -> String -> [String] -> String -- a = b = String
Numeric literals are overloaded (i.e. subject to ad-hoc polymorphism):
The difference is that the type variable here is constrained – it must be an instance of
1 :: (Num t) => t
- On Understanding Types, Data Abstraction, and Polymorphism (1985), by Luca Cardelli, Peter Wegner in ACM Computing Surveys.
- Type polymorphism at Wikipedia