Difference between revisions of "Ad-hoc polymorphism"

From HaskellWiki
Jump to: navigation, search
(Moved content to Polymorphism)
Line 1: Line 1:
#REDIRECT [[Polymorphism#Ad-hoc polymorphism]]
A value is [[polymorphism|polymorphic]] if, depending on its context, it can assume more than one type. If the value is specified separately for each type it can have, this is called '''ad-hoc polymorphism''', also known as '''overloading'''. Ad-hoc polymorphic values may be used at a limited number of pre-specified types.
For instance, in C++, the addition operator may be used on any numeric type, like <tt>int</tt> or <tt>float</tt>, 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 <tt>+</tt> in C++ is limited to those built-in and those for which the programmer has provided a definition. Similarly, in C, the operator <tt>+</tt> may operate on <tt>int</tt> or <tt>float</tt> or pointers. However, the programmer cannot supply their own definitions, and only the built-in types can be used.
In Haskell, type classes are used as a mechanism for "principled overloading", i.e. ad-hoc polymorphism. For instance, the following function:
show :: (Show a) => a -> String
may adopt any of the following types:
Int -> String
Float -> String
(Maybe Int, String, Either Char Float) -> String
The types which <hask>show</hask> can adopt are precisely those which have an instance of the standard <hask>Show</hask> class defined. Each instance gives a definition of the <hask>show</hask> function to be used when the types match. Unlike in C++ function overloading, Haskell also allows overloaded ''values'', like <hask>maxBound</hask>, that adopt a different value based on their type (e.g. <hask>maxBound :: Bool</hask> is equal to <hask>True</hask>, while <hask>maxBound :: Int</hask> may be <hask>2147483647</hask>).
Contrast ad-hoc polymorphism with [[parametric polymorphism]]: e.g. the function <hask>length :: [a] -> Int</hask> may be applied to lists of ''any'' type, but has only one definition which it uses regardless of which type it adopts.

Latest revision as of 21:59, 4 September 2012