Cameron Toy
Cameron Toy

Reputation: 41

Writing raw binary to a file in Haskell?

I'm trying to do some Huffman coding in Haskell, but am having a hard time figuring out how to save the resulting 1s and 0s as they are instead of as a string. So far, I've read the following--

https://wiki.haskell.org/Dealing_with_binary_data

https://wiki.haskell.org/Binary_IO

http://hackage.haskell.org/package/binary-0.10.0.0/docs/Data-Binary.html

--but am still pretty confused as to how to deal with my specific situation. Similarly, I'm having difficulty figuring out how to write the tree structure

data HTree = Leaf Char Int
           | Branch HTree HTree Int
             deriving (Show)

used to decode the data to a file. (HTree is the structure I'm using to store the Huffman Tree).

Upvotes: 0

Views: 282

Answers (1)

Erick Gonzalez
Erick Gonzalez

Reputation: 334

You probably want to take a look at the Put monad in Data.Binary.Put. You didn't provide any code example but something to get you started:

-- just an example with some made up encoding  

huffmanEncode :: HTree -> Put
huffmanEncode (Leaf c val) = do
    putWord16be 0xf00
    putCharUtf8 c
    putWord32be $ fromIntegral val
huffmanEncode (Branch l r x) = do
    putWord16be 0xbaf
    putWord32be $ fromIntegral x
    huffmanEncode l
    huffmanEncode r

You would then "run" your encoder thus: runPut $ huffmanEncode myTree

Upvotes: 2

Related Questions