Functional dependencies and overlapping instances

237 views Asked by At

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:

What is the best recommended solution in current GHC Haskell?

1

There are 1 answers

7
leftaroundabout On

The best solution is a closed type family:

type family C' a where
  C' A = B
  C' a = D