wiki

Orphan instance

A typeclass instance declared in a module that owns neither the class nor the type. Because instance resolution is global but imports are not, two orphans for the same pair can coexist in one program and the behaviour then depends on what happened to be linked, which is why the compiler warns about them.

An instance is an orphan when the module declaring it owns neither the class nor the type. The problem is a mismatch in scoping: instance resolution is global and implicit, but imports are local and explicit, so an orphan is in scope for the solver whether or not anyone imported the module that defines it.

Two libraries can then define different Ord instances for the same type, both compile, and the program that links both gets whichever the compiler happened to see. Worse, a Map built under one ordering and read under another silently loses entries: the invariant the structure relies on is no longer the one its keys obey.

The fix is the newtype, which makes the choice local and explicit rather than global and ambient.

-- orphan: neither Ord nor Text is ours
instance Ord Text where compare = compareCaseInsensitively
-- not an orphan: we own CI, so the instance travels with it
newtype CI = CI Text
instance Ord CI where
compare (CI a) (CI b) = compareCaseInsensitively a b

referenced by

Overlapping instances

read more