Ad-hoc polymorphism: Difference between revisions

From HaskellWiki
m (add 'or overloading')
mNo edit summary
 
(3 intermediate revisions by one other user not shown)
Line 1: Line 1:
[[Category:Glossary]]
#REDIRECT [[Polymorphism#Ad-hoc polymorphism]]
A value is [[polymorphism|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 '''<hask>+</hask>''' may have type (in Haskell notation) <hask>Int -> Int -> Int</hask> or <hask>String -> String -> String</hask>, 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 '''<hask>+</hask>''' in C++ is limited to those built-in and those explicitly defined.
[[Category: Pages to be removed]]
 
Many non-object-oriented languages use ad-hoc polymorphism too.  In C, the operator '''<hask>+</hask>''' may have the types <hask>Int -> Int -> Int</hask> or <hask>Float -> Float -> Float</hask> or <hask>Double -> Int -> Double</hask> or <hask>Ptr -> Int -> Ptr</hask>.  The range of possible types of <hask>+</hask> in C is limited to those built-in.
 
In Haskell, ad-hoc polymorphism is achieved by type classes.  For instance, the function <hask>show</hask> may have type of the form <hask>Int -> String</hask> or <hask>Float -> String</hask> or <hask>(Maybe Int, String, Either Char Float) -> String</hask> depending on its context, but the possible types of <hask>show</hask> are limited.  The user must ''specify'' the type <hask>show</hask> will take by defining the type of its first argument as an instance of <hask>Show</hask>.  (This is reflected in its signature <hask>show :: Show a => a -> String</hask>.) 
 
Contrast ad-hoc polymorphism with [[parametric polymorphism]] of the function <hask>length :: [a] -> Int</hask>.  <hask>length</hask> may be applied to lists of ''any'' type--that is, may take on an unlimited number of types (of the form <hask>[a] -> Int</hask>)--and the user may apply it to any list without needing to specify the type beforehand.

Latest revision as of 20:58, 7 June 2023