Dabblings with Huffman encoding in Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List (sortBy) | |
import Data.Ord (comparing) | |
import qualified Data.Map as M (Map, fromList) | |
data Freq a = V Int a | B Int (Freq a) (Freq a) deriving (Show) | |
size :: Freq a -> Int | |
size (V n _) = n | |
size (B n _ _) = n | |
freq :: (a,Int) -> Freq a | |
freq (x, n) = V n x | |
freqs :: [(a,Int)] -> Freq a | |
freqs = merge . map freq | |
where merge [x] = x | |
merge xs = merge $ sortBy (comparing size) $ merged xs | |
merged (x:y:ys) = B (size x + size y) x y : ys | |
huffs :: Freq a -> M.Map String a | |
huffs = M.fromList . huffs' "" | |
where huffs' s (V _ x) = [(reverse s, x)] | |
huffs' s (B _ x y) = huffs' ('0':s) x ++ huffs' ('1':s) y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment