3 ms·
Multiple inheritance from a purely virtual class. In Java, they're called interfaces; Comparable is the analogue to Ord. The advantage that Haskell's typeclass
by GeneralMayhem 12y ago
Multiple inheritance from a purely virtual class. In Java, they're called interfaces; Comparable is the analogue to Ord.
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.
- chongli 12y agoYeah, though you will want to be the owner of either the type class or the type itself. Instances which are neither are called orphan instances and they are generally frowned upon. Luckily, it's trivial to create a newtype wrapper which gives you a whole new set of hooks for writing instances of a type.
- dllthomas 12y agoOrphan instances in libraries are frowned upon. In an application they are more palatable, though a newtype might still be a better choice, depending.
- GeneralMayhem 12y agoThat makes sense, but again, in Java you can't do it if you're just the owner of the typeclass, and in order to make a wrapper you'd have to make a subclass, which mucks with all kinds of other things.
- Peaker 12y agoThe advantage you mention is one of many (over OOP interfaces), I'll repeat it as (A). (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.
- GeneralMayhem 12y ago(C) is covered by generics in most cases. The others, yes.
- judk 12y agoGenerics aren't ad-hoc polymorphic. Type classes are.
- judk 12y agoE) you do get a dilemma if you add two elements in a sorted structure , lexically in two different files, where two different Ord instances arr in scope, respectively. this function-is-instance problem is dual to OO's -object-is-instance problem.
- Peaker 12y agoA homogenous list is guaranteed to only have one instance unless you enable incoherent instances (a known bad extension) or confuse the compiler with orphan instances (though I've never encountered this and think it should be detectable at link time anyway). One type -> at most one instance for any class, in Haskell.