Type classes seem to be a great possibility to write generic and reusable functions in a very consistent, efficient and extensible way. But still no "mainstream-language" provides them - On the contrary: Concepts, which are a quite analogical idea, have been excluded from the next C++!
What's the reasoning against typeclasses? Apparently many languages are looking for a way to deal with similar problems: .NET introduced generic constraints and interfaces like IComparable
which allow functions like
T Max<T>(T a, T b) where T : IComparable<T> { // }
to operate on all types that implement the interface.
Scala instead uses a combination of traits and so called implicit parameters/view bounds, which are automatically passed to generic functions.
But both concepts shown here have great disadvantages - Interfaces are inheritance-based and thus relatively slow due to indirection and moreover there is no possibility of letting an existing type implement them.
If we needed an abstraction for a Monoid, we could pretty well write an interface and let our types implement this, but builtin types like int
could never operate on your functions natively.
Implicit parameters instead are inconsistent with regular interfaces/traits.
With type classes, there wouldn't be a problem (pseudo-code)
typeclass Monoid of A where
static operator (+) (x : A, y : A) : A
static val Zero : A
end
instance Int of Monoid where
static operator (+) (x : Int, y : Int) : Int = x + y
static val Zero : Int = 0
end
So why don't we use type classes? Do they have serious disadvantages after all?
Edit: Please don't confuse typeclasses with structural typing, pure C++ templates or duck typing. A typeclass is explicitly instantiated by types and not just satisfied by convention. Moreover it can carry useful implementations and not just define an interface.