I have a typeclass with a fundep:
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
class C a b | a -> b
I want to provide specific instances:
instance C A B
As well as a general, default instance:
instance C a D
Implementing this code as written, won't compile:
Functional dependencies conflict between instance declarations:
instance C A B
instance C a D
Switching to type families is no help:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
class C a where
type C' a
instance C A where
type C' A = B
instance C a where
type C' a = D
Conflicting family instance declarations:
C' A = B
C' a = D
Ideally, I'd like to get GHC to use the OverlappingInstances 'most specific' rule to resolve this.
I understand this is an issue that has been known for a while, with various hacky solutions suggested:
- [Haskell-cafe] Overlapping Instances with Functional Dependencies (July 2005[!])
- https://homepages.cwi.nl/~ralf/HList/
- Sound and Decidable Type Inference for Functional Dependencies
- Overlapping Instances + Functional Dependencies Unsound?
- How does haskell resolve overlapping instances?
What is the best recommended solution in current GHC Haskell?
The best solution is a closed type family: