码迷,mamicode.com
首页 > 其他好文 > 详细

哈弗曼编码解码

时间:2014-08-09 02:39:06      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:算法   scheme   编码   


#lang scheme

( define nil ‘() )

( define ( make-leaf symbol weight )
   ( list ‘leaf symbol weight ) )  

( define ( leaf? obj )
   ( eq? ( car obj ) ‘leaf ) )

( define ( symbol-leaf x )
   ( cadr x ) )

( define ( weight-leaf x )
   ( caddr x ) )

( 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 )
   ( cond [ ( leaf? tree )
            ( list ( symbol-leaf tree ) ) ]
          [ else ( caddr tree ) ] ) )

( define ( weight tree )
   ( cond [ ( leaf? tree )
            ( weight-leaf tree ) ]
          [ else ( cadddr tree ) ] ) )  

( define ( decode bits tree )
   ( define ( decode-1 bits cur-branch )
      ( cond [ ( null? bits ) nil ]
             [ else ( let ( [ next-branch 
                              ( choose-branch ( car bits ) cur-branch ) ] )
                       ( cond [ ( 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 "Pass" ) ] ) )

( define sample-tree 
   ( make-code-tree ( make-leaf ‘A 4 )
                    ( make-code-tree ( make-leaf ‘B 2 )
                                     ( make-code-tree ( make-leaf ‘D 1 )
                                                      ( make-leaf ‘C 1 ) ) ) ) )

( define sample-message ‘( 0 1 1 0 0 1 0 1 0 1 1 1 0 ) )

( decode sample-message sample-tree )




哈弗曼编码解码,布布扣,bubuko.com

哈弗曼编码解码

标签:算法   scheme   编码   

原文地址:http://blog.csdn.net/pandora_madara/article/details/38449707

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!