Personal tools

Ad-hoc polymorphism

From HaskellWiki

(Difference between revisions)
Jump to: navigation, search
(Hawiki conversion)
m (add 'or overloading')

Revision as of 07:20, 6 October 2009

A value is polymorphic if, depending on its context, it can assume more than one type. If the possible types are limited and must be individually specified before use, this is called ad-hoc polymorphism (or overloading).

In object-oriented languages, ad-hoc polymorphism is often called overloading. For instance, in C++, the operator
may have type (in Haskell notation)
Int -> Int -> Int
String -> String -> String
, and may be applied to new types provided you write a definition for it using those types as arguments. The range of possible types of
in C++ is limited to those built-in and those explicitly defined. Many non-object-oriented languages use ad-hoc polymorphism too. In C, the operator
may have the types
Int -> Int -> Int
Float -> Float -> Float
Double -> Int -> Double
Ptr -> Int -> Ptr
. The range of possible types of
in C is limited to those built-in. In Haskell, ad-hoc polymorphism is achieved by type classes. For instance, the function
may have type of the form
Int -> String
Float -> String
(Maybe Int, String, Either Char Float) -> String
depending on its context, but the possible types of
are limited. The user must specify the type
will take by defining the type of its first argument as an instance of
. (This is reflected in its signature
show :: Show a => a -> String
.) Contrast ad-hoc polymorphism with parametric polymorphism of the function
length :: [a] -> Int
may be applied to lists of any type--that is, may take on an unlimited number of types (of the form
[a] -> Int
)--and the user may apply it to any list without needing to specify the type beforehand.