我正在尝试反序列化一个数据流,它由(概念上)pair 组成("TypeName", "blah"
,其中对于某些类型的对象"blah"
是适当的输入。read
TypeName
有没有办法动态选择read
的结果类型?Data.Dynamic
我会使用类似的东西Data.Typable
吗?
我正在尝试反序列化一个数据流,它由(概念上)pair 组成("TypeName", "blah"
,其中对于某些类型的对象"blah"
是适当的输入。read
TypeName
有没有办法动态选择read
的结果类型?Data.Dynamic
我会使用类似的东西Data.Typable
吗?
这应该为您指明正确的方向:
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)