简体   繁体   中英

R5RS Scheme, Huffman tree function

The goal was to create a huffman tree (google if you do not know what it is) whose output does not contain the weight of the value, just the values located in leaves held by the placeholder "internal" with. I have created a working function that does look correct, besides with every "internal" there are extra null lists present which should not be there. If someone could take a look at the code and see my mistake or a way to optimize it I'd appreciate it.

(define (build-huffman lst)
  (let ((x (insert-list-of-pairs lst '())))
    (define (huffman-help heap)
      (if (null? (remove-min heap))
          heap
          (let ((rx (remove-min heap)))
            (if (list? (h-min heap))
                (huffman-help (insert (cons (make-internal-node (value (h-min heap))
                                                                (value (h-min rx)))
                                            (+ (weight (h-min rx))
                                               (weight (h-min heap))))
                                       (remove-min rx)))
                (huffman-help (insert (cons (make-internal-node (create-heap (value (h-min heap)) '() '())
                                                                (create-heap (value (h-min rx)) '() '()))
                                          (+ (weight (h-min rx))
                                             (weight (h-min heap))))
                                      (remove-min rx)))))))
  (car (car (huffman-help x)))))

Some of the functions are self explanatory and I know that the issue is within this code not any other function.

(insert-list-of-pairs)-takes a list of pairs, ex. "((no . 7) (yes . 4))," and inserts it into a heap.

(insert)-inserts one pair into a heap.

(remove-min)-removes minimum value of the heap.

(make-internal-node 0-tree 1-tree) -> (list 'internal 0-tree 1-tree)

Have you looked for a pattern? It seems to me like your code adds null lists after there are no more of the same node to add to the tree. It looks like homework so I can't give you an answer but look in your code and see if you can tell it to stop after adding the last of the same weight of a node.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM