[Haskell-beginners] More De/Serialisation Woes

Stephen Tetley stephen.tetley at gmail.com
Tue Sep 7 07:12:44 EDT 2010

Hi Tom

For the serializePreamble question...

serialisePreamble would need to map over the list of strings.

As you want to apply a monadic function to each value you would need
monadic-map rather than regular map (:: (a->b) -> [a] -> [b]).

Monad map comes in two flavours

a) mapM :: (a -> m b) -> [a] -> m [b]

b) mapM_ :: (a -> m b) -> [a] -> m ()

mapM_ is in some respects a "forgetful" version of mapM - it performs
the actions but "forgets" the results.

mapM_ is the one you want here as writing to handle in the IO monad is
approximately :: a -> IO ()

Because Strings are length prefixed you will a helper function along
the lines of

serializeString :: Handle -> String -> IO ()
serializeString h s = do { L.hPut h (encode (length s))
                         ; mapM_ (\ch -> L.hPutChar h ch) s }

Unfortunately using L.hPutChar isn't appropriate - it illustrates what
you would have to do, but isn't the right way of doing it. If you are
using String data from the Java world - its likely you will actually
have to deal with some encoding - probably converting each char to a
Word16 and writing a Word16 with the appropriate endian-ness.

The Data.Binary.Put module has a function putByteString for writing
(byte) strings. Unfortunately this is won't be appropriate either, as
the data layout from putByteString is unlikely to match the layout
that the Java tuple space expects. For your use case, you will have to
make some "primitive" output functions yourself.

More information about the Beginners mailing list