簡體   English   中英

使用量化約束導出 Ord(forall a.Ord a => Ord (fa))

[英]Derive Ord with Quantified Constraints (forall a. Ord a => Ord (f a))

有了量化的約束,我可以很好地推導出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-quantified-constraints 使用 ghc 8.6.5

問題是EqOrd的超類,並且約束(forall a. Ord a => Ord (fa))不包含聲明Ord (A f)實例所需的超類約束Eq (A f)

  • 我們有(forall a. Ord a => Ord (fa))

  • 我們需要Eq (A f) ,即(forall a. Eq a => Eq (fa)) ,這不是我們所擁有的。

解決方案:將(forall a. Eq a => Eq (fa))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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM