Er, you could define mergesort using templates in c++ and it would work pretty much the same.
Er, you could define mergesort using templates in c++ and it would work pretty much the same.
Ord a => [a] -> [a]
You therefore know that the implementation of the function can only make use of functions provided by Ord, and manipulation of the list structure. The function cannot inspect the values in the list except via comparison. This is an incredibly powerful guarantee. It's also really useful when you go to implement the function because this level of parametricity guarantees that there are only so many valid implementations and only a couple of them are even close to correct. mutableSort :: (MArray arr elem m, Ord elem, Ix ix) => arr ix elem -> m ()
This can work on mutable arrays in the IO, ST, or other mutable-array supporting monads. It also has a generalized index type (though newer array libraries threw that part away, so it's not considered a good idea anymore).The advantage that Haskell's typeclasses have over either Java or C++ is that the types aren't closed. I can define a new typeclass and tell the compiler that a type you defined is a member of that class at any point. In Java, if you don't define that your type is Comparable, there's nothing that I, as a consumer of your type, can do about it.
(A) Ability to instantiate old types with new classes
(B) Conditional instantiation: "Maybe a" is an instance of "Show" iff "a" is an instance of "Show"
(C) Can do return-type polymorphism, or polymorphism on any part of the signature
(D) Objects do not need to pay for the interface vtable pointer. Large array of some type-class instance can be much smaller than an array of an OOP interface subclass.
(E) When comparing two Ord instance values, there is only one Ord dictionary, rather than 2 to choose from. No false dilemma.
One type -> at most one instance for any class, in Haskell.
The error you get if you try to sort a vector with an unordered type is relatively easy to read:
main.cpp: In instantiation of 'void merge_sort(std::vector<_RealType>&) [with T = type]':
main.cpp:45:17: required from here
main.cpp:30:5: error: static assertion failed: Element type is not sortable
static_assert( concept::is_ord<T>(), "Element type is not sortable" );
^Interfaces or pure virtual classes are not the same because they're closed.