单态限制和序列化/反序列化

时间:2013-11-21 20:02:11

标签: haskell

我尝试开发繁重的网络应用程序,并使用ProtoBuf来描述网络消息。

这是我的代码的简化版本。由于单态限制,它不起作用。

class Message a where
  pack :: a -> ByteString
  unpack :: ByteString -> Maybe a

data HelloMsg = HelloMsg deriving Show
instance Message HelloMsg -- ... using protobuf

data PingMsg = PingMsg deriving Show
instance Message PingMsg -- ... using protobuf

data PongMsg = PongMsg deriving Show
instance Message PongMsg -- ... using protobuf
-- and more 50 another...

data MsgType = Hello | Ping | Pong -- | and more 50 another ...
data CommonMsg a = CommonMsg MsgType a deriving Show

instance (Message a) => CommonMsg a where
  pack (CommonMsg type msg) = concat [packType type, pack msg]
  unpack bin = let (type, rest) = unpackType bin in CommonMsg type <$> unpack rest
  -- here i need unpack message depend on type

receiver :: Chan (CommonMsg a) -> IO ()
receiver out = void $ forkIO $ forever $ do
  msg <- unpack <$> getCommonMsgFromNet
  writeChan out

main = do
  input <- newChan
  receiver input
  forver $ do
    msg <- readChan input
    putStrLn $ show msg

存在哪些变通方法?使用类似架构链接到项目是非常可取的

更新:重新解释我的问题 - 我需要多态方法反序列化ByteString到Message取决于消息类型。

0 个答案:

没有答案