haskell – 动态转世类型

我正在尝试反序列化一个数据流,包括(概念上)该对(“TypeName”,“blah”,其中“blah”是适合读取类型为TypeName的某个对象的输入.

有没有办法动态选择读取的结果类型?我会使用像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)
点赞