Change in Behaviour of Quantified Constraints in GHC 9
Asked Answered
M

1

6

Previously, in order to use quantified constraints on typeclasses like Ord, you had to include the superclass in the instance like so:

newtype A f = A (f Int)
deriving instance (forall a. Eq a => Eq (f a)) => Eq (A f)
deriving instance (forall a. Eq a => Eq (f a), forall a. Ord a => Ord (f a)) => Ord (A f)

(This is in fact precisely the solution given in this question).

In GHC 9, however, the above code doesn't work. It fails with the following error:

   • Could not deduce (Eq (f a))
      from the context: (forall a. Eq a => Eq (f a),
                         forall a. Ord a => Ord (f a))
        bound by a stand-alone deriving instance declaration:
                   forall (f :: * -> *).
                   (forall a. Eq a => Eq (f a), forall a. Ord a => Ord (f a)) =>
                   Ord (A f)
      or from: Eq a
        bound by a quantified context
    • In the ambiguity check for a stand-alone deriving instance declaration
      To defer the ambiguity check to use sites, enable AllowAmbiguousTypes
      In the stand-alone deriving instance for
        ‘(forall a. Eq a => Eq (f a), forall a. Ord a => Ord (f a)) =>
         Ord (A f)’

Unfortunately the AllowAmbiguousTypes suggestion doesn't work. (you get the same error, followed by the same error for every method on the class)

Does anyone know of a workaround for this?

Milliliter answered 27/8, 2021 at 15:51 Comment(0)
K
3

One simple way to solve it is to change the second deriving clause to:

deriving instance (Eq (A f), forall a. Ord a => Ord (f a)) => Ord (A f)

I don't yet have a good explanation for why this is happening though.

Kelwin answered 27/8, 2021 at 17:11 Comment(2)
GHC 9.0 "now more faithfully implements the instance lookup scheme ..."" says the Release Notes downloads.haskell.org/~ghc/9.0.1/docs/html/users_guide/… -- looks to be exactly like the example here.Hugohugon
@AntC, yes, that seems to be it. Although I do not understand the previous and current mechanisms well enough to give a good answer, perhaps you or somebody else can add it as another answer.Kelwin

© 2022 - 2024 — McMap. All rights reserved.