3 ms·
It's an implementation of "ad-hoc polymorphism", where, for example, it may make sense to "add" (+) together numbers of various types: integers, floating points
by ryandv 1y ago
It's an implementation of "ad-hoc polymorphism", where, for example, it may make sense to "add" (+) together numbers of various types: integers, floating points, rational numbers, etc.
Thus the (+) operator for addition is "overridden" or "polymorphic" in the types of numbers that can be added together.
The argument for having a polymorphic signature rather than just multiple separate "monomorphic" functions is similar to that for "generics," otherwise known as "parametric polymorphism": why not just have a function `forEachInt` for iterating over lists of ints, a separate function `forEachChar` for iterating over lists of characters, and so on?
Higher levels of abstraction and generality, less boilerplate and coupling to any particular choice of data structure or implementation.
You could of course go the route of golang which indeed just had you write "monomorphized" versions of everything. Several years later generics were added to the language.
Alternatively, you throw everything out and never have to worry about typing or polymorphism, at the cost of static safety.