(wat-aro)

無職から有職者にランクアップしました

SICP 問題 2.68

(define (encode message tree)
  (if (null? message)
      '()
      (append (encode-symbol (car message) tree)
              (encode (cdr message) tree))))

(define (encode-symbol msg tree)
  (if (leaf? tree)
      '()
      (cond
       ((memq msg (symbols (left-branch tree)))
        (cons 0
              (encode-symbol msg (left-branch tree))))
       ((memq msg (symbols (right-branch tree)))
        (cons 1
              (encode-symbol msg (right-branch tree))))
       (else (error symbol "is not Found")))))
gosh> (encode '(A D A B B C A) sample-tree)
(0 1 1 0 0 1 0 1 0 1 1 1 0)
gosh> (decode (encode '(A D A B B C A) sample-tree) sample-tree)
(A D A B B C A)