margareta.dev

Type polymorphism

May 27, 2020

Polymorphism can be defined as a way of representing multiple different types in a single abstraction.

Structural vs nominal type systems

How the type system decides if the types are equivalent (1) or have a subtype-relationship (2)?

  1. Structural typing

Answer: Structure of types. Properties of types must be identical in order for the types to be identical. Examples: OCaml, Typescript, Haskell. Common for dynamically-typed languages.

  1. Nominal typing

Answer: Explicit declarations. Type declarations have the same name. Examples: C#, Java, Rust, Swift, F#. Nominal is a subset of structural.

See link

Types of polymorphism

  1. Subtyping

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.

Examples: C#, Java, F# (wtf)

No support in OCaml due to the module systems and type signatures for modules.

  1. Parametric polymorphism (generics)

Handle values generically without depending on their type. Generics in Java or C# and templates in C++.

  1. Row polymorphism

OCaml objects - polymorphic records.

See this SO answer.

  1. Ad-hoc polymorphism

No relationship between the types is necessary (as opposed to subtyping). There concrete implementations for the different types. Examples: Haskell operator overloading and type classes.

https://medium.com/@pmbanka/polymorphwhat-e3b36bbb2f99