Difference between revisions of "Polymorphism"

From HaskellWiki
Jump to navigation Jump to search
Line 12: Line 12:
 
foldr :: (a -> b -> b) -> b -> [a] -> b
 
foldr :: (a -> b -> b) -> b -> [a] -> b
 
</haskell>
 
</haskell>
<hask>foldr</hask> is a parametrically polymorphic [[function]]. When actually used, it may take on any of a variety of types, for example:
+
The type of <hask>foldr</hask> 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:
 
<haskell>
 
<haskell>
 
:: (Char -> Int -> Int) -> Int -> String -> Int -- a = Char, b = Int (note String = [Char])
 
:: (Char -> Int -> Int) -> Int -> String -> Int -- a = Char, b = Int (note String = [Char])
Line 19: Line 19:
 
Numeric literals are overloaded (i.e. subject to ad-hoc polymorphism):
 
Numeric literals are overloaded (i.e. subject to ad-hoc polymorphism):
 
<haskell>
 
<haskell>
1 :: (Num t) => t -- notice the =>, indicating a type class is involved
+
1 :: (Num t) => t
 
</haskell>
 
</haskell>
  +
The difference is that the type variable here is constrained – it must be an instance of <hask>Num</hask>.
   
 
== References ==
 
== References ==

Revision as of 16:20, 7 May 2012

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.

  1. Parametric polymorphism; mostly found in functional languages
  2. Ad-hoc polymorphism or overloading
  3. Inclusion polymorphism; mostly found in object oriented languages

Examples

foldr :: (a -> b -> b) -> b -> [a] -> b

The type of foldr 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):

1 :: (Num t) => t

The difference is that the type variable here is constrained – it must be an instance of Num.

References