【SICP练习】95 练习2.68

简介:

练习2.68

先要导入练习2.67中的sample-tree。这道题要求我们写出能够根据给定的树产生出给定符号的二进制位表的函数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!”))))
如此一来便可以得出encode了。
(define (encode message tree)
    (if (null? message)
      ‘()
       (append (encode-symbol (car message) tree)
                (encode (cdr message) tree))))

通过测试我们发现和上一题中的结果完全符合,如前面所说要导入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)



感谢访问,希望对您有所帮助。 欢迎关注或收藏、评论或点赞。


为使本文得到斧正和提问,转载请注明出处:
http://blog.csdn.net/nomasp


目录
相关文章
|
网络架构
【SICP练习】145 练习4.1
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/44728049 练习4-1 原文 Exercise 4.
901 0