Erlang's term_to_binary in Haskell?

好久不见. 提交于 2020-01-01 05:37:06

问题


Is there a no-fuss serialization method for Haskell, similar to Erlang's term_to_binary/binary_to_term calls? Data.Binary seems unnecessarily complicated and raw. See this example where you are basically manually encoding terms to integers.


回答1:


Use Data.Binary, and one of the deriving scripts that come with the package.

It's very simple to derive Binary instances, via the 'derive' or 'deriveM' functions provided in the tools set of Data.Binay.

derive :: (Data a) => a -> String

For any 'a' in Data, it derives a Binary instance for you as a String. There's a putStr version too, deriveM. Example:

*Main> deriveM (undefined :: Drinks)
instance Binary Main.Drinks where
  put (Beer a) = putWord8 0 >> put a
  put Coffee = putWord8 1
  put Tea = putWord8 2
  put EnergyDrink = putWord8 3
  put Water = putWord8 4
  put Wine = putWord8 5
  put Whisky = putWord8 6
  get = do
    tag_ <- getWord8
    case tag_ of
      0 -> get >>= \a -> return (Beer a)
      1 -> return Coffee
      2 -> return Tea
      3 -> return EnergyDrink
      4 -> return Water
      5 -> return Wine
      6 -> return Whisky
      _ -> fail "no parse"

The example you cite is an example of what the machine generated output looks like -- yes, it is all bits at the lowest level! Don't write it by hand though -- use a tool to derive it for you via reflection.



来源:https://stackoverflow.com/questions/2260475/erlangs-term-to-binary-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!