国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 【SICP练习】95 练习2.68

【SICP练习】95 练习2.68

来源:程序员人生   发布时间:2015-03-20 09:14:50 阅读次数:2283次

练习2.68

先要导入练习2.67中的sample-tree。这道题要求我们写出能够根据给定的树产生出给定符号的2进制位表的函数encode-symbol,这个函数还要能够在遇到未在树中出现的符号时报错。这个函数将要在给定的树中查找给定符号的叶子节点,并记录下寻觅进程中的左右方向,固然了,如书中所说,向左则用0,向右则用1。因此该函数可以以下列出。我们先来写那个检测毛病的谓词。

(define (symbol-in-tree? gven-symbol tree) (not (false? (find (lambda (s) (eq? s given-symbol)) (symbols tree))))) (define (encode-symbol symbol tree) (cond ((leaf? tree) ‘()) ((symbol-in-tree? symbol (left-branch tree)) (cons 0 (encode-symbol symbol (left-branch tree)))) ((symbol-in-tree? symbol (right-branch tree)) (cons 1 (encode-symbol symbol (right-branch tree)))) (else (error “Error: symbol not in this tree!”)))) 如此1来即可以得出encode了。 (define (encode message tree) (if (null? message) ‘() (append (encode-symbol (car message) tree) (encode (cdr message) tree))))

通过测试我们发现和上1题中的结果完全符合,如前面所说要导入sample-tree。

(encode( a d a b b c a) sample-tree) ;Value: (0 1 1 0 0 1 0 1 0 1 1 1 0)
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生