2

我有一个定义为(缩写)的 GADT,

{-# LANGUAGE StandaloneDeriving #-}
data D t where
    C :: t -> D t
    R :: D b -> D (Either a b)
deriving instance Show t => Show (D t)

编译器正确地抱怨它不能为 R 派生 Show。在这种情况下,我们知道 (Either ab) 属于 Show 类,但如果 b 属于 Show 类,我们不知道这是真的。错误信息是,

Could not deduce (Show b) from the context (t ~ Either a b)
  arising from a use of `showsPrec' at tmp.hs:37:0-37
Possible fix: add (Show b) to the context of the constructor `R'
In the second argument of `(.)', namely `(showsPrec 11 b1)'
In the second argument of `showParen', namely
    `((.) (showString "R ") (showsPrec 11 b1))'
In the expression:
    showParen ((a >= 11)) ((.) (showString "R ") (showsPrec 11 b1))
When typechecking a standalone-derived method for `Show (D t)':
  showsPrec a (C b1)
              = showParen ((a >= 11)) ((.) (showString "C ") (showsPrec 11 b1))
  showsPrec a (R b1)
              = showParen ((a >= 11)) ((.) (showString "R ") (showsPrec 11 b1))

似乎需要能够限定存在类型,例如对存在类型 b 说“Show b => Show (D (Either ab))”,或者升级含义“(Show a, Show b) = > Show (Either ab)" 所以它是双向的。

非常感谢!

(请随意清理标题或描述。)

4

1 回答 1

4

Show约束添加到存在,

data D t where
    C :: t -> D t
    R :: Show b => D b -> D (Either a b)

你在做生意。

Prelude> :r
[1 of 1] Compiling A                ( A.hs, interpreted )
Ok, modules loaded: A.
*A> R (C 7)
R (C 7)
于 2011-05-01T00:48:15.970 回答