Replies: 2 comments
-
|
Here is a couple of details to discuss:
|
Beta Was this translation helpful? Give feedback.
0 replies
-
|
Use cases for type classes (or anything similar to Rust-style traits) that we've encountered over time:
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Type classes (first appearing in Haskell around 1991-92) are an elegant mechanism to make ad-hoc polymorphism (overloaded methods) disciplined and dx-friendly in a strongly-typed language. The concept has carried over to PureScript and later Rust (as traits).
The idea is to associate a dictionary to basic types (ground rules) and give parametrised types dictionary transformers. From these ingredients then the compiler can build (derive) such dictionaries for increasingly complex types with minimal user intervention.
To give an example
Above transformation only kicks in when the
T can Numberconstraint kicks in. To make that happen we can declareFloatas a `Number instance:This way we get valid
Complex<Float>numbers. But there are complex integers too (they are called Gaussian integers), so forNumber<Int>either we or the compiler has to provide a type class instance:Similarly
Orderedconstraints can be lifted from element types to collections (trees, etc.).The pretty thing about type classes is that the programmer doesn't need to pass around dictionaries, the compiler does it transparently (as hidden arguments). The compiler also takes care of the other plumbing.
Problems
In a type system with subclassing ambiguities may arise because the user may define instances for overlapping subtypes. In such cases it is not automatic which instance the compiler should choose. Dylan has a similar problem with multiple dispatch and generic functions, but it just suppresses ambiguous specialisations and topologically sorts the viable ones.
Beta Was this translation helpful? Give feedback.
All reactions