1

我有一个递归数据定义:

data Checked a =  forall b. Checked (Either (Warning, Maybe (Checked b), a) a)

我需要递归地定义 Show:

instance (Show a) => Show (Checked a) where
  show (Right v) = show v
  show (Left (w, Nothing, v) = show w ++ show v
  show (Left (w, Just ch, v) = show w ++ show v ++ "caused by" ++ show ch --recursive here

GHC给

 Could not deduce (Show b) arising from a use of `show'
  from the context (Show a)
  bound by the instance declaration at Checked.hs:29:10-35
  Possible fix:
   add (Show b) to the context of
    the data constructor `Checked'
    or the instance declaration
  In the second argument of `(++)', namely `show ch'

如果我将 (Show b) 添加到实例定义的约束中,GHC 会给出:

 Ambiguous constraint `Show b'
  At least one of the forall'd type variables mentioned by the constraint
  must be reachable from the type after the '=>'
In the instance declaration for `Show (Checked a)'

我应该采取下一步来编译它吗?

4

2 回答 2

5

您需要将Show b限制添加到数据类型:

data Checked a = forall b. Show b => Checked (Either (Warning, Maybe (Checked b), a) a)

instance Show a => Show (Checked a) where
  show (Checked (Right v)) = show v
  show (Checked (Left (w, Nothing, v))) = show w ++ show v
  show (Checked (Left (w, Just ch, v))) = show w ++ show v ++ "caused by" ++ show ch
于 2012-10-24T09:46:42.157 回答
3

Show向数据类型定义添加约束。

data Checked a =  forall b. Show b => Checked (Either (Warning, Maybe (Checked b), a) a)

您还可以将约束类型用作

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}

data Checked a c =  forall b. c b =>  Checked (Either (Maybe (Checked b c), a) a)

instance (Show a) => Show (Checked a Show) where
 show (Checked (Right v)) = show v
 show (Checked (Left (Nothing, v))) = show v
 show (Checked (Left (Just ch, v))) = show v ++ "caused by" ++ show ch
于 2012-10-24T09:52:47.997 回答