导出具有量化约束的Ord(总a。Ord a => Ord(fa))


10

有了量化的约束,我可以得出Eq (A f)结论吗?但是,当我尝试导出Ord(A f)时会失败。当约束类具有超类时,我不理解如何使用量化约束。我如何派生Ord (A f)以及其他具有超类的类?

> newtype A f = A (f Int)
> deriving instance (forall a. Eq a => Eq (f a)) => Eq (A f)
> deriving instance (forall a. Ord a => Ord (f a)) => Ord (A f)
<interactive>:3:1: error:
     Could not deduce (Ord a)
        arising from the superclasses of an instance declaration
      from the context: forall a. Ord a => Ord (f a)
        bound by the instance declaration at <interactive>:3:1-61
      or from: Eq a bound by a quantified context at <interactive>:1:1
      Possible fix: add (Ord a) to the context of a quantified context
     In the instance declaration for 'Ord (A f)'

PS。我还检查了ghc建议0109-quantified-constraints。使用ghc 8.6.5

Answers:


8

问题在于,它Eq是的超类Ord,并且该约束(forall a. Ord a => Ord (f a))不包含Eq (A f)声明Ord (A f)实例所需的超类约束。

  • 我们有 (forall a. Ord a => Ord (f a))

  • 我们需要Eq (A f),即(forall a. Eq a => Eq (f a))我们所拥有的并不暗含。

解决方案:添加(forall a. Eq a => Eq (f a))Ord实例。

(我实际上不理解GHC给出的错误消息与问题有何关系。)

{-# LANGUAGE QuantifiedConstraints, StandaloneDeriving, UndecidableInstances, FlexibleContexts #-}

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)

或更整洁:

{-# LANGUAGE ConstraintKinds, RankNTypes, KindSignatures, QuantifiedConstraints, StandaloneDeriving, UndecidableInstances, FlexibleContexts #-}

import Data.Kind (Constraint)

type Eq1 f = (forall a. Eq a => Eq (f a) :: Constraint)
type Ord1 f = (forall a. Ord a => Ord (f a) :: Constraint)  -- I also wanted to put Eq1 in here but was getting some impredicativity errors...

-----

newtype A f = A (f Int)
deriving instance Eq1 f => Eq (A f)
deriving instance (Eq1 f, Ord1 f) => Ord (A f)

我是如此接近deriving instance (forall a. (Eq a, Ord a) => (Eq (f a), Ord (f a))) => Ord (A f)。你知道为什么会有区别吗?
威廉·鲁斯纳克

1
这也不意味着forall a. Eq a => Eq (f a)。(从逻辑上看(A /\ B) => (C /\ D)并不意味着A => C
夏丽瑶

1
实际上,您写的内容等同于forall a. Ord a => Ord (f a)
夏丽瑶

感谢您的解释!
William Rusnack
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.