Exercise2-68 <---> Exercise2-70

Exercise 2-69

English text of exercise The following procedure takes as its argument a list of symbol-frequency pairs (where no symbol appears in more than one pair) and generates a Huffman encoding tree according to the Huffman algorithm.

(define (generate-huffman-tree pairs)

Make-leaf-set is the procedure given above that transforms the list of pairs into an ordered set of leaves. Successive-merge is the procedure you must write, using make-code-tree to successively merge the smallest-weight elements of the set until there is only one element left, which is the desired Huffman tree. (This procedure is slightly tricky, but not really complicated. If you find yourself designing a complex procedure, then you are almost certainly doing something wrong. You can take significant advantage of the fact that we are using an ordered set representation.)

The procedure is quite straight forward .. it uses the procedure adjoin-set which works on weights to form and ordered set.


Ru: Русский текст упражнения


Scheme solution:

(define (adjoin-set x set)
  (cond ((null? set) (list x))
        ((< (weight x) (weight (car set))) (cons x set))
        (else (cons (car set)
                    (adjoin-set x (cdr set))))))

(define (generate-huffman-tree pairs)
  (successive-merge (make-leaf-set pairs)))

(define (successive-merge set)
  (if (null? (cdr set))
      (car set)
      (successive-merge (adjoin-set
                         (make-code-tree (car set)
                                         (cadr set))
                         (cddr set)))))

Other solutions goes here (use "#!code haskell", "#!code ocaml", etc. for syntax highlighting)

Exercise2-68 <---> Exercise2-70


Comments


:) :)) :( ;) :\ |) X-( B) Markup

Exercise2-69 (last edited 2008-07-01 20:34:47 by SteveChapel)