Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang's term_to_binary in Haskell?

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.

like image 742
me2 Avatar asked Feb 14 '10 07:02

me2


1 Answers

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.

like image 152
Don Stewart Avatar answered Oct 11 '22 20:10

Don Stewart