polymorphism
Ways to get polymorphism
- subtyping:
- Key example: You have 2 sub-types of an
Animal
:Cat
,Dog
. Both of them implement amake_noise()
method. Say we haveAnimal a = new Cat()
. Then, at runtime,a.make_noise()
will cause a table lookup into thea
object, which happens to be a cat. This table lookup will contain the location of themake_noice()
function to run for a Cat. See (wikipedia article on late binding). This is conceptually similar to dynamic linking (see Linker) - You can do this in Java
- Key example: You have 2 sub-types of an
- parametric polymorphism
- in haskell, this is done with type variables. So,
id:: a -> a
must be able to ttake any typea
as input - In Java and Rust this is done with generics
- in haskell, this is done with type variables. So,
- ad hoc polymorphism
- basically, overloading methods
- choose the method at compile according to the type of the arguments
- contrasted with subtyping, which uses late binding, described above
- In haskell, this is achieved via typeclasses, e.g., you can define what == means for any type that is an instance of the
Eq
type class - In java, this is done with method overloading
- see also multiple dispatch
1. random thoughts
- let polymorphism kind of reminds me of zeugma in the sense that a verb (function) will have to use different senses (types) in the sentence.