2

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?

Ari Fordsham
  • 2,437
  • 7
  • 28

1 Answers1

3

The best solution is a closed type family:

type family C' a where
  C' A = B
  C' a = D
leftaroundabout
  • 117,950
  • 5
  • 174
  • 319
  • Yes, but I'm looking specifically for an open type family. – Ari Fordsham May 06 '21 at 12:57
  • 2
    @AriFordsham What you're looking for seems like a footgun of type-unsafety and incoherence. If your specific instance for some choice of `a` (let's stick with `A`) is in scope in some places but not others, some parts of your code will think the associated type is `B` and other parts of your code will think it's `D`. A closed type family makes it safe because you'll never have some in scope and some not. – Joseph Sible-Reinstate Monica May 06 '21 at 18:23
  • @JosephSible-ReinstateMonica why is it worse than regular OverlappingInstances, and GHC's 'most specific' rule? – Ari Fordsham May 06 '21 at 18:42
  • @AriFordsham Because this lets you basically accidentally do a bad `unsafeCoerce`, and regular OverlappingInstances don't. – Joseph Sible-Reinstate Monica May 06 '21 at 18:43
  • Do you now for a fact that this would be an issue? Can you think of an example? I would have thouht GHC was cleverer than that. – Ari Fordsham May 06 '21 at 18:49
  • 1
    @AriFordsham Yes. GHC's cleverness is that it gives you the errors that it gave you. It's hard to give a concrete example because of that. – Joseph Sible-Reinstate Monica May 06 '21 at 18:52
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/232057/discussion-between-ari-fordsham-and-joseph-sible-reinstate-monica). – Ari Fordsham May 06 '21 at 18:55