We build the main sorting logic polymorphically — independent from the type of an element of an Array.
Now then: Why do we need to pass the ordering function around manually? Can we make the process easier?
We can try making sorting function accept only the types that have a compare
method and call it inside of the
sort. But this makes the code:
- More coupled.
- Non tree-shakeable.
- Less extensible.
Why is that so? Because for each functionality like sort
which requires compare
method we need to change the
definition of the class. It gets pretty tiresome for our own code and makes it impossible to extend other (for
example library) code. One must write another class wrapper... which again is tiresome and error prone.
Can we fix it the other, maybe automatic, way?
- In TypeScript/JavaScript/ReScript? No! Cope with it — wire everything manually.
- In Haskell/Scala/Rust? Yes!
Why and How? The answer is — type classes. What are they? The answer is simple: we define each instance just like we did before and let the copiler wire the instances. That's essentially it. Type classes make our code easier and other's code possible to extend.
See also: