5 ms·
Quite. Typeclasses are Haskell's way of doing ad hoc polymorphism. C++ has ad hoc polymorphism too, but it's via templates not classes.
by grabcocque 9y ago
Quite. Typeclasses are Haskell's way of doing ad hoc polymorphism. C++ has ad hoc polymorphism too, but it's via templates not classes.
- Veedrac 9y agoTypeclasses also do virtual dispatch, though. That comparison isn't much closer.
- gpderetta 9y agoNot an Haskell expert (or even a beginner really, just generally interested in language design), but as far as I understand in 99% of the cases virtual dispatch in Haskell is purely an implementation detail: i.e. type classes can be implemented via monomorphization exactly like C++ templates (and in fact the compiler will do exactly that when optimising or when explicitly directed to do so); it isn't done by default mostly to preserve separate compilation and code explosion. There are cases where that can't be done at all (polymorphic recursion, when the recursion can't be proven to terminate at compile time, I'm sure there are other) and runtime dispatching is required, but that's more of an exception. In C++ that's implemented with explicit, semi manually implemented, type erasure wrappers. edit: as I said, I'm not an Haskell programmer; maybe in idiomatic Haskell the cases where runtime dispatch is required are much more common.
- Veedrac 9y agoImagine you have a problem for which you need virtual dispatch. In C++, you typically reach for inheritance. In Haskell, you typically reach for typeclasses. Comparatively, imagine you have a problem for which you need ad-hoc, but statically resolvable, overloads. In C++, you typically reach for templates. In Haskell, you instead typically reach again for typeclasses. This is what I mean when I say neither comparison is really closer than the other. Haskell couldn't replace typeclasses with templates, just as it couldn't replace them with objects.