Unit content
Ad hoc polymorphism and type-class constraints
Ad hoc polymorphism lets one operation work at several types by selecting a type-specific implementation.
For example, a generic equality function cannot compare arbitrary values merely from a type variable $A$; it needs evidence that values of $A$ support equality. A constrained type can express
$$\forall A.\ Eq(A)\Rightarrow A\to A\to Bool.$$
Here Eq(A) is a capability requirement. An implementation for integers may use integer comparison, while an implementation for strings uses string comparison.
Languages realize this idea through mechanisms such as type classes, traits, protocols or constrained generics. Conceptually they separate two things:
- the interface of operations required for a type;
- an instance or implementation showing how a particular type provides them.
This differs from parametric polymorphism. A truly parametric function must behave uniformly for every type; a constrained function may use precisely the operations promised by its constraints.
Constraints can themselves participate in type inference. If sort requires an ordering operation, its type can state that the element type must satisfy an ordering interface rather than hard-coding one concrete element type.
Ad hoc polymorphism provides reusable generic algorithms while making their required capabilities explicit in the type system, without requiring all participating types to share one inheritance hierarchy.