使用量化约束推导Ord(forall a. Ord a => Ord(f a))

9

使用量化限制条件,我可以成功推导出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)'

顺便提一下,我还研究了ghc提案0109-量化约束。使用的是ghc 8.6.5

1个回答

8
问题在于EqOrd的超类,并且约束条件(forall a. Ord a => Ord (f a))并不意味着需要声明Ord(A f)实例所需的超类约束Eq(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) 上非常接近了。你知道为什么会有差异吗? - William Rusnack
1
这并不意味着 forall a. Eq a => Eq (f a)。从逻辑上看,(A /\ B) => (C /\ D) 不意味着 A => C - Li-yao Xia
1
实际上,你所写的等同于 forall a. Ord a => Ord (f a) - Li-yao Xia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接