开发者

Erlang's term_to_binary in Haskell?

开发者 https://www.devze.com 2022-12-19 22:53 出处:网络
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开发者_如何学JAVA and raw. See this example wh

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开发者_如何学JAVA and raw. See this example where you are basically manually encoding terms to integers.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号