# Polymorphism

### From HaskellWiki

(Difference between revisions)

(Improve wording, and add Wikipedia link.) |
Benmachine (Talk | contribs) (→Examples) |
||

Line 10: | Line 10: | ||

== Examples == |
== Examples == |
||

<haskell> |
<haskell> |
||

− | foldr :: forall a b. (a -> b -> b) -> b -> [a] -> b |
+ | foldr :: (a -> b -> b) -> b -> [a] -> b |

</haskell> |
</haskell> |
||

− | <hask>foldr</hask> is a parametric polymorphic [[function]]. When actually used, it may take on any of a variety of types, for example: |
+ | <hask>foldr</hask> 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 |
+ | :: (Char -> Int -> Int) -> Int -> String -> Int -- a = Char, b = Int |

− | ::(String->String->String)->String->[String]->String |
+ | :: (String -> String -> String) -> String -> [String] -> String -- a = b = String |

</haskell> |
</haskell> |
||

− | An "integer literal" is a parametric polymorphic data type: |
+ | Numeric literals are overloaded (i.e. subject to ad-hoc polymorphism): |

<haskell> |
<haskell> |
||

− | 1 :: forall t. (Num t) => t |
+ | 1 :: (Num t) => t |

</haskell> |
</haskell> |
||

## Revision as of 18:00, 30 April 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.

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

## 1 Examples

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

foldr

:: (Char -> Int -> Int) -> Int -> String -> Int -- a = Char, b = Int :: (String -> String -> String) -> String -> [String] -> String -- a = b = String

Numeric literals are overloaded (i.e. subject to ad-hoc polymorphism):

1 :: (Num t) => t

## 2 References

- On Understanding Types, Data Abstraction, and Polymorphism (1985), by Luca Cardelli, Peter Wegner in ACM Computing Surveys.

- Type polymorphism at Wikipedia