[Haskell-beginners] Haskell Serialization

Daniel Fischer daniel.is.fischer at web.de
Tue May 11 13:56:43 EDT 2010

On Tuesday 11 May 2010 19:00:43, Ashish Agarwal wrote:
> Thanks for your responses.
> > Only it might give rise to confusion if somebody wants to transmit
> > those types according to another protocol.
> So are Binary instances perceived to be just for (de)serializing from/to
> Haskell?

Sort of. A Binary instance should be generic (for an  unspecified value of 
'generic'). Binary instances are for making the (de)serislisation of types 
using the type in question easy (and are expected to have as little 
overhead as possible - at least, that's what I expect).

> Would it be better style for me to define a new type class with
> methods getProt and putProt, where Prot is whatever protocol I'm
> supporting?

You don't need to define a new class, you could just use putProt and 
getProt directly.
However, if you are reasonably sure that (de)serialising your type 
according to a different protocol is exceptional, go ahead and make a 
Binary instance. If there are several standard protocols for a type, an 
instance using one could be confusing.

> > numbers are always big-endian
> I have been wondering about the difference in put/get instances of Word
> types versus the getWord8be, getWord8le, etc. functions. Since the
> default instances use big-endian, is there any difference between the
> following:
>     get (0::Word8)
>     getWord8be 0

Make that

put (0 :: Word16)
putWord16be 0


-- Words8s are written as bytes
instance Binary Word8 where
    put     = putWord8
    get     = getWord8

-- Words16s are written as 2 bytes in big-endian (network) order
instance Binary Word16 where
    put     = putWord16be
    get     = getWord16be

[analogously for other WordN types].
With optimisations, there should be no difference, without, the difference 
would be one dictionary lookup, I think.

> What exactly are the guarantees for Binary instances, only that get and
> put are inverses?

With hand-written instances, not even that :)

> Are all other features possibly different between
> compiler versions or different implementations of Haskell?

No, serialised values should be portable, i.e. if you serialise a value 
using implementation x and deserialise it using implementation y, you ought 
to get the same value.

More information about the Beginners mailing list