我有一个递归数据定义:
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'
如果我将(显示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)'
我应该采取下一步来进行编译吗?
答案 0 :(得分: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
答案 1 :(得分: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