简体   繁体   English

R5RS 方案,哈夫曼树函数

[英]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.目标是创建一个霍夫曼树(如果您不知道它是什么,请使用 google),其输出不包含值的权重,仅包含由占位符“内部”保存的叶子中的值。 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. (insert-list-of-pairs) - 获取对列表,例如。 "((no . 7) (yes . 4))," and inserts it into a heap. “((no . 7) (yes . 4)),”并将其插入到堆中。

(insert)-inserts one pair into a heap. (insert) - 将一对插入堆中。

(remove-min)-removes minimum value of the heap. (remove-min) - 删除堆的最小值。

(make-internal-node 0-tree 1-tree) -> (list 'internal 0-tree 1-tree) (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.它看起来像作业,所以我无法给你答案,但请查看你的代码,看看你是否可以在添加最后一个相同重量的节点后让它停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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