Haskell(Make Tree)中的Huffman代码

时间:2018-08-15 18:04:03

标签: haskell huffman-code

因此,这是关于霍夫曼·特雷斯的一个长期问题。我试图做一棵树和一个代码表。

这是我的类型

module Types where

type Occurence  = (Value, Number)
type Occurences = [Occurence]
type Number     = Int
type Value      = Char
type Code       = [Directions]
type CodeTable  = [(Value, Code)]


data Directions = L | R deriving (Eq, Ord, Show)


data HTree      = Leaf {frequency :: Number, character:: Value} |
                  Node {frequency:: Number, 
                        leftChild:: HTree,
                        rightChild:: HTree} deriving Show


makeLeaf :: Occurence -> HTree
makeLeaf (c,n) = Leaf n c

这是我尝试创建树功能

module MakeTree(makeTree, treeFromTable) where
import Types

makeTree :: Occurences -> HTree
makeTree = makeCodes . toTreeList

toTreeList :: Occurences -> [HTree]
toTreeList = map (uncurry Leaf)

h :: [HTree] -> [HTree]
h (t1:t2:ts) = insertTree (join t1 t2) ts

makeCodes :: [HTree] -> HTree
makeCodes [t] = t
makeCodes ts = makeCodes (h ts)

join :: HTree -> HTree -> HTree
join t1 t2 = Node (freq1+freq2) t1 t2
    where
      freq1 = v t1
      freq2 = v t2

v :: HTree -> Int
v (Leaf _ n ) = n
v (Node n _ _) = n

insertTree :: HTree -> [HTree] -> [HTree]
insertTree t [] = [t]
insertTree t (t1:ts) 
     | v t < v t1 = t:t1:ts
     | otherwise = t1 : insertTree t ts

这是我制作CodeTable的尝试

constructTable :: HTree -> CodeTable
constructTable = convert []
      where
      convert :: Code -> HTree -> CodeTable
      convert hc (Leaf c n) = [(c, hc)]
      convert hc (Node n tl tr) = (convert (hc++[L]) tl) ++ (convert (hc++[R]) tr)

代码表错误

CodeTable.hs:14:33: error:
    • Couldn't match type ‘Int’ with ‘Char’
      Expected type: Value
        Actual type: Number
    • In the expression: c
      In the expression: (c, hc)
      In the expression: [(c, hc)]
   |
14 |       convert hc (Leaf c n) = [(c, hc)]

您发现任何错误,还是可以告诉我为什么这些代码都不适合我?

1 个答案:

答案 0 :(得分:2)

Expected type: Value
Actual type: Number

从错误消息中可以很明显地看出,以下表达式出了什么问题:

convert hc (Leaf c n) = [(c, hc)]

HTree定义为:

data HTree      = Leaf {frequency :: Number, character:: Value} |
                  Node {frequency:: Number, 
                        leftChild:: HTree,
                        rightChild:: HTree} deriving Show

Leaf接受frequency(数字)作为第一个参数,接受character(数值)作为第二个参数。因此,我们只需要交换表达式中的参数即可:

convert hc (Leaf n c) = [(c, hc)]

还在v函数的定义中:

v (Leaf n _ ) = n

type Occurence的定义中:

type Occurence  = (Number, Value)

以及makeLeaf中的

makeLeaf (n, c) = Leaf n c

完成这些步骤后,您的代码应成功编译