ഹഫ്മാൻ ഗോൾഫ് (ഹാസ്കലിൽ)Draft

ഹഫ്മാൻ കോഡുകളുടെ ആത്മാവിൽ, അതായത്, ഒപ്റ്റിമൽ ലോസ്ലെസ് എൻകോഡിംഗ്, ഹാസ്കലിൽ എനിക്ക് കണ്ടെത്താൻ കഴിഞ്ഞ ഹഫ്മാൻ കോഡ് ജനറേഷന്റെ ഏറ്റവും ചെറിയ ഇംപ്ലിമെന്റേഷൻ ഇതാ. സിഗ്നേച്ചർ ഇതാണ്:

huffman :: Eq a => [(a, Int)] -> [(a, String)]

ഇവിടെ ആർഗ്യുമെന്റ് (element, frequency) ജോഡികളുടെ ഒരു ലിസ്റ്റാണ്. ഇത് (element, binary encoding) ജോഡികളുടെ ഒരു ലിസ്റ്റ് റിട്ടേൺ ചെയ്യുന്നു.

v1

ഇതിന് ഈ ഇംപോർട്ടുകൾ ആവശ്യമാണ്:

-- ഇംപോർട്ടുകൾ
import Data.List (sortBy)
import Data.Ord (comparing)

ഇതാ പ്രധാന പ്രോഗ്രാം

data Tree a = Leaf a Int | Node Int (Tree a) (Tree a) deriving (Show)
freq (Leaf _ f) = f
freq (Node f _ _) = f
merge t1 t2 = Node (freq t1 + freq t2) t1 t2
decode t x = (x, decode' "" t)
    where
        decode' acc (Leaf y _) = if x == y then reverse acc else ""
        decode' acc (Node _ l r) = (decode' ('0':acc) l) ++ (decode' ('1':acc) r)
combine [x] = x
combine xs = let (t1:t2:rest) = sortBy (comparing freq) xs in combine ((merge t1 t2):rest)
huffman xs = map ((decode (combine (map (uncurry Leaf) xs))) . fst) xs

ഇത് സബ്ഒപ്റ്റിമൽ ആണ്, കാരണം ഓരോ ഇറ്ററേഷനിലും സോർട്ട് ചെയ്യുന്നു, ഒരു പ്രയോറിറ്റി ക്യൂ മതിയായിരുന്നു. ഞാൻ ബാഹ്യ ലൈബ്രറികൾ ഉപയോഗിക്കാൻ ആഗ്രഹിച്ചില്ല.

വായനക്ഷമത പൂർണ്ണമായും മറന്ന്, ജനറിക് ടൈപ്പ് a ഒഴിവാക്കിയാൽ:

huffman :: [(Char, Int)] -> [(Char, String)]

287 ബൈറ്റുകൾ:

data T=L Char Int|N Int T T
f(L _ w)=w;f(N w _ _)=w
m t1 t2=N(f t1+f t2)t1 t2
d t x=(x,s"" t)where s a(L y _)=if x==y then reverse a else"";s a(N _ l r)=s('0':a)l++s('1':a)r
c[x]=x;c x=let(t1:t2:r)=sortBy(\a b->f a`compare`f b)x in c(m t1 t2:r)
huffman x=map((d(c(map(uncurry L)x))).fst)x

v2

data T=L Char|N T T
huffman x=[(c,e t c"")|(c,_)<-x]where
 t=f$foldr ins[][(n,L c)|(c,n)<-x]
 f[(n,t)]=t
 f((n1,t1):(n2,t2):l)=f$ins(n1+n2,N t1 t2)l
 ins n[]=[n]
 ins n l@(n':ls)|fst n<=fst n'=n:l|1>0=n':ins n ls
 e(L c)c' s=if c==c' then s else""
 e(N l r)c s=e l c(s++"0")++e r c(s++"1")

✦ No LLMs were used in the ideation, research, writing, or editing of this article.