CS 119 Lab 7 – Trees
Objectives
Perform the following tasks in the order given.
data HTree = Leaf Char | Branch HTree HTree deriving Show
Branch (Branch (Leaf 'x') (Leaf 'e')) (Leaf 't')
In this tree, the character 'x' is coded by 00, 'e' by 01, and 't' by 1.
To build a Huffman tree we start with a list of characters along with their frequencies. For example:
[('g',8),('r',9),('a',11),('t',13),('e',17)]
We convert this list of pairs into a list of trees and then repeatedly combine the trees with the lightest weights until just one tree remains. The weight of a single leaf will be the weight of the character at that leaf. The weight of a binary node is the sum of the weights of its two subtrees. We will need another tree data type for this weighted tree:
data WeightedTree = Tip Int Char | Node Int WeightedTree WeightedTree deriving Show
After the weighted tree is constructed we can simply
remove the weights and get our HTree.
The code for construction of the weighted tree is given to you. Look
through the code and trace through it with the given frequencies. Test
it out and see if you get the weighted tree that you expect.
We will make our HTree as follows:
makeHTree :: [(Char,Int)] -> HTree
makeHTree x = unweight (makeWeightedTree x)
| Assignment: Write the function unweight which takes a weighted tree and converts it to an HTree by stripping off the weights. Test if out with the weights above. |
| Assignment: Write the function decode :: HTree -> [Bit] -> [Char]. Test if out with the HTree from question #4 and the bit string [1,1,0,1,1,1,1,0,0,0,0,1] . |
type CodeTable = [(Char,[Bit])]
The code for transform is :
transform :: HTree -> CodeTable
transform (Leaf x) = [(x,[])]
transform (Branch t1 t2) = hufmerge (transform t1) (transform t2)
The function hufmerge takes two
code tables and merges them, adding a zero bit to the front of all the codes
coming from the first table, and a one bit to the front of all the codes
coming from the second table.
| Assignment: Write the function hufmerge :: CodeTable -> CodeTable -> CodeTable Test it out by doing a transform of your HTree. |
| Assignment: Write the function codeLookup :: Char -> CodeTable -> [Bit]. Test if out. |
| Assignment: Write the function encode :: HTree -> [Char] -> [Bit]. Test if out with the HTree from question #4 and the string "great". |