An orphan instance is a type class instance for class C and type T which is neither defined in the module where C is defined nor in the module where T is defined.
Type class instances are special in that they don't have a name and cannot be imported explicitly. This also means that they cannot be excluded explicitly. All instances defined in a module A are imported automatically when importing A, or importing any module that imports A, directly or indirectly.
Say you want to define an alternative instance to an existing instance. This is a bad thing, since if two instances for the same class/type pair are in scope, then you cannot describe in Haskell 98 which instance to use. If you want to use multiple instances for the same class/type, you have to ensure that they are never imported together in a module somewhen. It is almost impossible to assert that, or put differently, it would reduce the composability of libraries considerably.The
Since some packages use MTL and others 'transformers' it becomes difficult to use that instance at all, although both instances are equivalent! Practical advice:The explicit-exception package with its
Actually, non-orphan instances can avoid definition of multiple instances. For defining an instance you have to import the class and the type and then you will automatically have the according non-orphan instances imported, too. If you want to define a new instance then the compiler will reject it immediately.
A last advice: If you encounter a missing instance for a class or a type of a package, resist to define your own orphan instance, because it will likely collide with such instances of other packages, or it will collide with new instances added in later versions of that package. Instead ask the package author to add your instance. Sometimes it turns out that the instance was not included for the good reason that there is more than one reasonable instance definition. If your instance cannot be included, follow the advices in the article about multiple instances.
1 Avoiding orphan instances
If you encounter an
instance C T
which is orphan, then you can try to
- move the instance declaration to the module defining class ,C
- move the instance declaration to the module defining type ,T
- wrap the type in a custom type, like soT
newtype N = N T instance C N
- define a custom class (unlikely to be useful), like so
class C => S instance S T instance S X -- for all X where an instance C X already exist
- not use the class at all.C
2 See also
- Multiple instances
- Libraries mailing list on Orphan instances can be good
- Ideas on possible compiler warnings for coping with orphan instances
- Libraries mailing list on Relaxin the PVP with regards to adding instances
- Partial Revelation feature of Modula-3 which causes similar problems like Haskell's type class instances