Created
November 30, 2015 13:59
-
-
Save ruandao/fb0851c54ccf2f022aee to your computer and use it in GitHub Desktop.
The decoding procedure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;#lang planet neil/sicp | |
#lang racket | |
(require (planet soegaard/sicp:2:1/sicp)) | |
(define wave einstein) | |
(define (make-code-tree left right) | |
(list left | |
right | |
(append (symbols left) (symbols right)) | |
(+ (weight left) (weight right)))) | |
(define (left-branch tree) (car tree)) | |
(define (right-branch tree) (cadr tree)) | |
(define (symbols tree) | |
(if (leaf? tree) | |
(list (symbol-leaf tree)) | |
(caddr tree))) | |
(define (weight tree) | |
(if (leaf? tree) | |
(weight-leaf tree) | |
(cadddr tree))) | |
(define (decode bits tree) | |
(define (decode-1 bits current-branch) | |
(if (null? bits) | |
'() | |
(let ((next-branch (choose-branch (car bits) current-branch))) | |
(if (leaf? next-branch) | |
(cons (symbol-leaf next-branch) | |
(decode-1 (cdr bits) tree)) | |
(decode-1 (cdr bits) next-branch))))) | |
(decode-1 bits tree)) | |
(define (choose-branch bit branch) | |
(cond ((= bit 0) (left-branch branch)) | |
((= bit 1) (right-branch branch)) | |
(else (error "bad bit -- CHOOSE-BRANCH" bit)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment