Jump to content

Huffman coding: Difference between revisions

m
→‎{{header|Haskell}}: ( Generalising map to fmap (<$>) for marginally more readability )
m (→‎{{header|Haskell}}: ( Generalising map to fmap (<$>) for marginally more readability ))
Line 2,690:
=={{header|Haskell}}==
Credits go to [http://www.haskell.org/haskellwiki/99_questions/46_to_50#Problem_50 huffman] where you'll also find a non-tree solution. Uses sorted list as a priority queue.
<lang haskell>import Data.List
import Control.Arrow
import Data.Ord
 
data HTree a = Leaf a | Branch (HTree a) (HTree a)
= Leaf a
deriving (Show, Eq, Ord)
| Branch (HTree a)
(HTree a)
deriving (Show, Eq, Ord)
 
test :: String -> IO ()
test =
test s = mapM_ (\(a,b)-> putStrLn ('\'' : a : "\' : " ++ b))
mapM_ (\(a, b) -> putStrLn ('\'' : .a serialize: ."\' huffmanTree: ." freq++ $b)) s.
serialize . huffmanTree . freq
 
serialize :: HTree a -> [(a, String)]
serialize (Branch l r) = map (second('0':)) (serialize l) ++ map (second('1':)) (serialize r)
(second ('0' :) <$> serialize l) ++ (second ('1' :) <$> serialize r)
serialize (Leaf x) = [(x, "")]
 
huffmanTree :: (Ord w, Num w) => [(w, a)] -> HTree a
:: (Ord w, Num w)
huffmanTree = snd . head . until (null.tail) hstep
=> [(w, a)] -> HTree a
. sortBy (comparing fst) . map (second Leaf)
huffmanTree =
snd .
head . until (null . tail) hstep . sortBy (comparing fst) . map (second Leaf <$>)
 
hstep
hstep :: (Ord a, Num a) => [(a, HTree b)] -> [(a, HTree b)]
:: (Ord a, Num a)
hstep ((w1,t1):(w2,t2):wts) = insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts
hstep :: (Ord a, Num a) => [(a, HTree b)] -> [(a, HTree b)]
hstep ((w1, t1):(w2, t2):wts) =
hstep ((w1,t1):(w2,t2):wts) = insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts
 
freq
freq :: Ord a => [a] -> [(Int, a)]
:: Ord a
freq = map (length &&& head) . group . sort</lang>
freq :: Ord a => [a] -> [(Int, a)]
freq =c map= (length &&& head) .<$> group . (sort c)</lang>
{{out}}
<lang haskell>*Main> test "this is an example for huffman encoding"
9,655

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.