4 ms·
Haskell type classes are by no means magic and the run-time does absolutely nothing with them. Type classes are de-sugared in the compiler and turned into an e
by the_why_of_y 10y ago
Haskell type classes are by no means magic and the run-time does absolutely nothing with them.
Type classes are de-sugared in the compiler and turned into an extra function parameter that is a record of functions, aka "dictionary".
This is a bit similar to vtables in C++, but different because firstly, the C++ vtable is already reachable from explicit parameters/implicit "this", and secondly, C++ actually has dynamic dispatch whereas type classes are not dynamic dispatch, at least from a language point of view - they essentially correspond to "overloading" in C++.
Type classes could just as well be implemented by expanding all invocations of the function with different instances and generating monomorphic code for every combination of instances. Compilers don't do that because it would waste too much space.
Also, what exactly is a "compiled language"? The words don't mean much of significance.
- catnaroek 10y ago> This is a bit similar to vtables in C++, but different because firstly, the C++ vtable is already reachable from explicit parameters/implicit "this" Rust vtables aren't attached to all objects, but they're always attached to trait objects (whose methods are dynamically dispatched). So it's halfway between C++ and Haskell in this regard. FWIW, I would call dictionaries “vtables”. C++ and Rust just happen to impose restrictions on how vtables can be used, so that each trait object can be bundled with its own vtable (`exists a. C a => a`), rather than potentially bundling several objects with the same vtable (`exists a. C a => T a`). But this doesn't mean that Haskell uses a fundamentally different implementation technique. > Type classes could just as well be implemented by expanding all invocations of the function with different instances and generating monomorphic code for every combination of instances. As long as you don't use higher-ranked types.