我正在尝试为FromJSON
类型类编写一个通用实例。我们的想法是在解析JSON时使用数据类型名称。我认为这是GHC应该能做的事情,但到目前为止我的尝试都失败了。使用Typeable
类型类的最简单版本如下所示。
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)) ""’
我尝试用Generics做同样的事情,但又得到了同样的错误。
答案 0 :(得分:3)
启用ScopedTypeVariables
扩展我能够编译此示例。使用此扩展程序,a
中的Proxy a
对应于实例声明中的相同a
。