2013-06-03 76 views
4

我試圖反序列化數據流,包含(概念上)對("TypeName", "blah",其中"blah"read適用於某些類型爲TypeName的對象。動態轉化類型

有沒有辦法動態選擇read的結果類型?我會使用類似Data.Dynamic還是Data.Typable

+3

只有當你有某種註冊表您需要的所有類型。 – augustss

+0

註冊?我有一組封閉的類型,但我不確定如何使用它。嗯。我正在研究爲'Data.Typable.TypeRep'創建一個'Read'實例。 – jpaugh

+2

對於一組封閉類型,您可以在類型名稱上使用case語句,每個arm使用read和toDyn類型簽名。 – augustss

回答

2

這應該指向你在正確的方向:

import Data.Typeable 
import Data.Dynamic 
import Control.Applicative 

readMay :: Read a => String -> Maybe a 
readMay s = case reads s of 
    (a,[]):_ -> Just a 
    _ -> Nothing 

reconstruct :: Typeable a => (Maybe a -> r) -> (String, String) -> r 
reconstruct k (typ,val) = 
    case typ of 
     "string" -> k $ cast =<< (readMay val :: Maybe String) 
     "int" -> k $ cast =<< (readMay val :: Maybe Int) 
     "double" -> k $ cast =<< (readMay val :: Maybe Double) 

reconstructToDyn (typ,val) = 
    case typ of 
     "string" -> toDyn <$> (readMay val :: Maybe String) 
     "int" -> toDyn <$> (readMay val :: Maybe Int) 
     "double" -> toDyn <$> (readMay val :: Maybe Double) 
+0

謝謝。我將通過增加大量的模板Haskell來使這個複雜化,但我得出了(幾乎)相同的結論。 – jpaugh