wiki:OverlappingInstances

Version 5 (modified by ross@…, 8 years ago) (diff)

--

Overlapping Instances

Ticket(s)

See ExtensionDescriptionHowto for information on how to write these extension descriptions. Please add any new extensions to the list of HaskellExtensions.

Brief Explanation

Instances are allowed to overlap, as long as there is a most specific one in any case. Contexts of instances play no part in testing for overlapping.

References

Variations

Hugs compares instance declarations, while GHC delays tests until the instances are used.

  • Hugs considers instances to be overlapping if they are unifiable, e.g.
    instance C Int b
    instance C a Bool
    
    Similarly the "most specific" test is applied to instances (though not as cleverly as it could be).
  • GHC only requires -fallow-overlapping-instances if it needs to resolve a constraint that overlaps with both, e.g. C Int Char is fine, but C a Bool overlaps. Similarly a most specific instance is needed only for constraints encountered in type checking.

An alternative to what GHC implements would be to declare whether a class may be overlapping on a class by class basis, perhaps with something like

class overlapping Foo a where
   ...

Pros

  • useful on occasion.

Cons

  • including a new module can silently change behavior of a program.
  • makes it very easy for incorrect programs to still typecheck
  • can cause confusing error messages
  • can sometimes be simulated with the extra-method trick used in the Show class of the prelude for showing lists of characters differently than lists of other things.