1
我正在尝试为FromJSON
typeclass写一个不知何故的通用实例。这个想法是在解析JSON时使用数据类型名称。我认为这是GHC应该能够做到的事情,但到目前为止,我的尝试失败了。最简单的版本,使用Typeable
typeclass如下。在JSON实例中使用数据类型名称
data GetResponse a = GetResponse { getCode :: Int, getItem :: a } deriving (Show)
instance (Typeable a, FromJSON a) => FromJSON (GetResponse a) where
parseJSON =
withObject "GetResponse" $ \o -> do
getCode <- o .: "code"
getItem <- o .: toLower (pack typeName)
return GetResponse {..}
where
typeName = showsTypeRep (typeRep Proxy :: Proxy a) ""
它失败,出现以下错误编译:
[1 of 1] Compiling Main (generics.hs, interpreted)
generics.hs:74:48: error:
• Could not deduce (Typeable a0) arising from a use of ‘typeRep’
from the context: (Typeable a, FromJSON a)
bound by the instance declaration at generics.hs:66:10-61
The type variable ‘a0’ is ambiguous
• In the first argument of ‘showsTypeRep’, namely
‘(typeRep (Proxy :: Proxy a))’
In the second argument of ‘($)’, namely
‘showsTypeRep (typeRep (Proxy :: Proxy a)) ""’
In the second argument of ‘($)’, namely
‘pack $ showsTypeRep (typeRep (Proxy :: Proxy a)) ""’
我想这样做与仿制药相同的事情,但得到了同样的错误了。
全码:http://codepad.org/Gh3ifHkP