【发布时间】:2018-08-15 18:04:03
【问题描述】:
所以这是一个关于 Huffman Tress 的长问题。我正在尝试制作树和代码表。
这是我的类型
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)]
你有没有发现任何错误,或者你能告诉我为什么这些代码都不适合我吗?
【问题讨论】:
标签: haskell huffman-code