【发布时间】:2020-04-10 16:05:45
【问题描述】:
我正在尝试编写一个函数(codeWords t),它遍历一棵霍夫曼树(向左添加#\0,向右添加#\1...)并成对返回这些值叶上的符号及其关联的编码为字符#\0 和#\1 上的字符串。类似于 this 或 this 正在尝试做的事情。
我的原始代码:
(define (last l)
(car (reverse l)))
(define (codeWords t)
(define (helper t l)
(cond ((null? t) l)
((eq? (car t) 'internal) (append (helper (caddr t) l)
(helper (last t) l)))
((eq? (car t) 'leaf) (helper '() (cons (cons (caddr t) (cadr t)) l)))))
(helper t '()))
(codeWords (huffman (get-freq (get-count "hello"))))
在朋友的建议下我对其进行了修改,但我的 leaf? 函数出现错误:
(mcar:违反合同
预期:mpair?
给定:1):
(define (leaf? T) (eq? (car T) 'leaf))
(define (subtree T c)
(cond ((eq? c #\0) (cadr T))
((eq? c #\1) (caddr T))))
(define (codeWords t)
(define (helper x y)
(if (leaf? x)
(list (cons (value x) (reverse y)))
(append (helper (subtree x #\0)
(cons #\0 y))
(helper (subtree x #\1)
(cons #\1 y)))))
(helper t '()))
我也想出了这段代码,看起来它可以工作,但它没有通过我的测试用例:
(define (codeWords t)
(define (encode char tree)
(cond
((null? tree) t)
((eq? (caar tree) char) '())
(else
(let ((left (encode char (cadr tree))) (right (encode char (caddr tree))))
(cond
((not (or left right)) #f)
(left (cons #\0 left))
(right (cons #\1 right)))))))
(encode t '()))
我认为可能有一个解决方案,而不必像在我的原始代码中那样使用eq? 和'leaf 来创建leaf? 函数,或者尝试实现类似编码函数here 的东西,但我'我目前有作家阻止。
【问题讨论】:
标签: scheme racket computer-science huffman-code r5rs