4

我正在尝试反序列化一个数据流,它由(概念上)pair 组成("TypeName", "blah",其中对于某些类型的对象"blah"是适当的输入。readTypeName

有没有办法动态选择read的结果类型?Data.Dynamic我会使用类似的东西Data.Typable吗?

4

1 回答 1

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)
于 2013-06-04T14:21:54.587 回答