我正在尝试在Haskell中进行一些Huffman编码,但是很难弄清楚如何保存结果1和0而不是字符串。到目前为止,我已阅读以下内容-
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
-但是对于如何处理我的具体情况仍然很困惑。同样,我在弄清楚如何编写树结构方面遇到困难
data HTree = Leaf Char Int
| Branch HTree HTree Int
deriving (Show)
用于将数据解码为文件。 (HTree是我用来存储霍夫曼树的结构。)
答案 0 :(得分:2)
您可能想看看Put
中的Data.Binary.Put
单子。您没有提供任何代码示例,但是可以帮助您入门:
-- 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
然后,您将“运行”编码器,例如:runPut $ huffmanEncode myTree