试图在haskell中打印一个huffman代码树



我制作的函数showTree采用了一个带有节点和叶子的huffman树;整齐地";把它印在壳里。

以下是功能:

showTree :: Tree -> String
showTree (Leaf c i) = [c] ++ show i
showTree (Node v t1 t2) =
left ++ "n" ++ middle ++ right
where middle  = replicate (heightTree (Node v t1 t2)) ' ' ++ replicate (heightTree (Node v t1 t2)) ' ' ++ replicate (heightTree (Node v t1 t2)) ' ' ++ show v
left    = showTree t1
right   = showTree t2 

此时,它会将节点和叶子直接打印在一起。输出结果如下:

i2
4l2
8a1
2g1
4h2
21r2
5t1
3n1
2s1
13 4
8e4

在每个元素中看到的第一个数字是节点号,后面是叶字符和整数。我正试图让它看起来像这样:


' '(4)
8
i(2)
4
l(2)
13
a(1)
2
t(1)
5
g(1)
2
s(1)
3
n(1)
21
e(4)
8
h(2)
4
r(2)

或者类似的东西。我基本上只是在努力想办法只把树叶展示在树的尽头。

您可以使用boxes库进行此操作。

showTree :: Tree -> Box
showTree (Leaf c i) = text $ concat [[c], "(", show i, ")"]
showTree (Node v t1 t2) = vcat right
[ moveLeft 6 (go t1)
, text (show v)
, moveLeft 6 (go t2)
]

在ghci:中

> printBox $ showTree (Node 21 (Node 13 (Node 8 (Leaf ' ' 4) (Node 4 (Leaf 'i' 2) (Leaf 'l' 2))) (Node 5 (Node 2 (Leaf 'a' 1) (Leaf 't' 1)) (Node 3 (Node 2 (Leaf 'g' 1) (Leaf 's' 1)) (Leaf 'n' 1)))) (Node 8 (Leaf 'e' 4) (Node 4 (Leaf 'h' 2) (Leaf 'r' 2)))
(4)                  
8            
i(2)                        
4                  
l(2)                        
13      
a(1)                        
2                  
t(1)                        
5            
g(1)                              
2                        
s(1)                              
3                  
n(1)                        
21
e(4)            
8      
h(2)                  
4            
r(2)

最新更新