2017-10-09 58 views
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

回答

3

啓用ScopedTypeVariables擴展,我能夠編譯這個例子。通過此擴展,aProxy a中對應於實例聲明中的相同a