May 27, 2020
Polymorphism can be defined as a way of representing multiple different types in a single abstraction.
How the type system decides if the types are equivalent (1) or have a subtype-relationship (2)?
- Structural typing
Answer: Structure of types. Properties of types must be identical in order for the types to be identical.
Common for dynamically-typed languages.
- Nominal typing
Answer: Explicit declarations. Type declarations have the same name.
Nominal is a subset of structural.
Restrict the range of types that can be used in a given abstraction (function or type) through relation between types. Common for OOP languages through interface or subclassing. Requires “substitute” relationship, subtypes/supertype.
Subtypes can be used in places of supertypes.
No support in
OCaml due to the module systems and type signatures for modules.
- Parametric polymorphism (generics)
Handle values generically without depending on their type.
C# and templates in
- Row polymorphism
OCaml objects - polymorphic records.
See this SO answer.
- Ad-hoc polymorphism
No relationship between the types is necessary (as opposed to subtyping). There concrete implementations for the different types.
Haskell operator overloading and type classes.