2.69 Exercise 2.69
We are asked to write the procedure successive-merge, which will be used in generating Huffman trees as follows:
(define (generate-huffman-tree pairs) (successive-merge (make-leaf-set pairs)))
Most of the hard work has already been done for us in the procedures written during this section. make-leaf-set will order the set of pairs, so we can take the first two elements from the set to get the two elements with the lowest weights. During the successive merging, we will have to maintain this ordering by placing the newly-merged trees in the correct place by their merged weights. We can do this by using the adjoin-set procedure that make-leaf-set also uses. adjoin-set is given as its arguments the newly-merged tree, constructed from the first two elements of the leaf-set, and the rest (cddr) of the leaf-set.
With a new leaf set constructed, we have to call successive-merge again, to continue merging until we’re done. The base case is that leaf-set is a list containing the final tree as its only element. In this case, the cdr is nil, and we return the tree itself.
The final procedure is below:
(define (successive-merge leaf-set) (if (null? (cdr leaf-set)) (car leaf-set) (successive-merge (adjoin-set (make-code-tree (car leaf-set) (cadr leaf-set)) (cddr leaf-set)))))