Haskell - 双向类实例类型含义还是GADT存在类型资格?

时间:2011-05-01 00:42:13

标签: haskell ghc typeclass algebraic-data-types gadt

我的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。在这种情况下,我们有(或者a b)是Show类,但是如果f是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说“显示b =>显示(D(任一ab))”,或升级暗示“(显示a,显示b)=>显示(任一ab)“因此它是双向的。

非常感谢!

(请随时清理标题或说明。)

1 个答案:

答案 0 :(得分: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)