繁体   English   中英

R5RS 方案,哈夫曼树函数

[英]R5RS Scheme, Huffman tree function

目标是创建一个霍夫曼树(如果您不知道它是什么,请使用 google),其输出不包含值的权重,仅包含由占位符“内部”保存的叶子中的值。 我创建了一个看起来正确的工作函数,除了每个“内部”之外,还有不应该存在的额外空列表。 如果有人可以查看代码并看到我的错误或优化它的方法,我将不胜感激。

(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)))))

一些函数是不言自明的,我知道问题出在这段代码中,而不是任何其他函数。

(insert-list-of-pairs) - 获取对列表,例如。 “((no . 7) (yes . 4)),”并将其插入到堆中。

(insert) - 将一对插入堆中。

(remove-min) - 删除堆的最小值。

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

你找过模式吗? 在我看来,您的代码在没有更多相同的节点要添加到树之后添加了空列表。 它看起来像作业,所以我无法给你答案,但请查看你的代码,看看你是否可以在添加最后一个相同重量的节点后让它停止。

暂无
暂无

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

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