Overlapping instances
also: overlapping, incoherent instances
Two instances overlap when some type matches both. Resolution does not backtrack, so the compiler must commit and instead reports an error. The OVERLAPPING pragmas make the more specific instance win, which is unsound when the overlap is not visible where the constraint is solved.
Two instances overlap when a type matches both. Instance resolution is not backtracking search, so the compiler cannot simply try one: it must commit, and with no way to know which is intended it reports an error rather than guess.
The classic case. [Char] matches both heads.
class Pretty a where pp :: a -> Stringinstance Pretty a => Pretty [a] where pp = concatMap ppinstance Pretty String where pp = id -- String = [Char]
The OVERLAPPING and OVERLAPPABLE pragmas resolve it by declaring that the more specific instance wins. That is safe when the overlap is visible at the point of use, and unsound when it is not: a function with a Pretty [a] constraint is compiled once, against the general instance, and stays compiled that way even when later called at String. The same expression then behaves differently depending on where it was elaborated.
Which is why INCOHERENT exists and why it is a warning sign: it tells the compiler to pick arbitrarily and not complain. The safe alternative is the same one that fixes orphans, a newtype, which makes the choice explicit at the call site instead of leaving it to resolution order.
see also
read more