Thursday, May 7, 2009

Huffman encoding in Haskell

My attempt at Huffman encoding in Haskell ... not complete ... hardly...anyway, I now need to switch to Minix FS in fuse

type CharacterFrequencyTuple = (Int,Char)

{-
  repeats hello
  = [(1,'e'),(1,'h'),(1,'o'),(2,'l')]

-}
repeats :: String -> [CharacterFrequencyTuple]
repeats string = quickSort $ zip counts uniqueLetters
  where
  counts = map (frequency string) uniqueLetters
  frequency :: String -> Char -> Int
  frequency (x:xs) c
  | c == x = 1 + frequency xs c
  | otherwise = frequency xs c
  frequency _ c = 0
  uniqueLetters = unique string

unique :: String -> String -- get the unique letters in the string
unique (x:xs) = [x] ++ unique [y | y <- xs, y /= x ]
unique [] = []


data Tree a = Node a (Tree a) (Tree a) | Leaf a
  deriving (Show)


huffman :: [CharacterFrequencyTuple] -> Tree Char
huffman (x:xs) = Leaf 'A'

quickSort (x:xs) = l1 ++ [x] ++ l2 -- items less than x + x + items bigger than x
  where
  l1 = quickSort [y | y <- xs, y <>
  l2 = quickSort [y | y <- xs, y >= x] -- sorted items greater than x
quickSort [] = []

main=do
  x <- getLine
  let y1=unique x
  let y2=repeats x
  putStrLn (show y1)
  putStrLn (show y2)


No comments: