diff options
author | Joe Zhao <ztuowen@gmail.com> | 2015-04-04 17:38:20 +0800 |
---|---|---|
committer | Joe Zhao <ztuowen@gmail.com> | 2015-04-04 17:38:20 +0800 |
commit | 13c0046a6dbd41b15358e76856922144ac76e768 (patch) | |
tree | dfee06a0f90b0b0b6048eafec7c46da253c79328 /H50.hs | |
parent | b47befab3696c40c710ee80f366fa376ec967b30 (diff) | |
download | h99-13c0046a6dbd41b15358e76856922144ac76e768.tar.gz h99-13c0046a6dbd41b15358e76856922144ac76e768.tar.bz2 h99-13c0046a6dbd41b15358e76856922144ac76e768.zip |
+46 +47 +48 +49 +50
Diffstat (limited to 'H50.hs')
-rw-r--r-- | H50.hs | 21 |
1 files changed, 21 insertions, 0 deletions
@@ -0,0 +1,21 @@ +import Data.List +import Data.Ord (comparing) +import Control.Arrow + +data HTree a = Leaf a | Branch (HTree a) (HTree a) + deriving Show + +huffman :: [(a, Int)] -> [(a,String)] + +huffman xs = serialize "" $ huffcon $ sortBy (comparing fst) $ map (\(x,y) -> (y, Leaf x)) xs +huffcon [(_,a)] = a +huffcon ((v1,t1):(v2,t2):rst) = huffcon $ sortBy (comparing fst) $ (v1+v2,Branch t1 t2):rst + +serialize s (Leaf l) = [(l,s)] +serialize s (Branch t1 t2) = (serialize ('0':s) t1) ++ (serialize ('1':s) t2) + +huffman' :: [(a,Int)] -> [(a,String)] +huffman' xs = huffcon' $ sortBy (comparing fst) [(y,[(x,"")]) |(x,y) <- xs] +huffcon' [(_,a)] = a +huffcon' ((v1,l1):(v2,l2):rst) = huffcon' $ sortBy (comparing fst) $ + (v1+v2,(map (fst &&& ('0':).snd) l1)++(map (fst &&& ('1':).snd) l2)):rst |