Sunday 29 September 2013

haskell pretty print binary tree not displaying properly

haskell pretty print binary tree not displaying properly

I am trying to pretty print a binary tree in Haskell so that if you turn
your head to the left, it should look like a tree. Each level in the tree
should be indented 2 spaces from the previous level.
This is the expected output:
-- 18
-- 17
-- 16
-- 15
-- 14
-- 13
-- 12
-- 11
-- 10
-- 9
-- 8
-- 7
-- 6
-- 5
-- 4
-- 3
-- 2
-- 1
For this tree:
treeB = (Node (Node (Node (Node Empty 1 (Node Empty 2 Empty)) 3 (Node
Empty 4 Empty)) 5 (Node (Node Empty 6 Empty) 7 (Node (Node Empty 8 Empty)
9 Empty))) 10 (Node (Node (Node Empty 11 Empty) 12 (Node Empty 13 (Node
Empty 14 Empty))) 15 (Node (Node Empty 16 Empty) 17 (Node Empty 18
Empty))))
This is how tree is defined:
data BinTree a =
Empty
| Node (BinTree a) a (BinTree a)
deriving (Eq,Show)
However, my result does not look like that. Here is my result:
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
Here is my code:
prettyTree :: (Show a) => BinTree a -> String
prettyTree Empty = "\n"
prettyTree (Node Empty x Empty) = " " ++ show x ++ "\n"
prettyTree (Node Empty x r) = prettyTree' r ++ " " ++ show x ++ "\n"
prettyTree (Node l x Empty) = show x ++ "\n" ++ " " ++ prettyTree' l
prettyTree (Node l x r) = prettyTree' r ++ show x ++ "\n" ++ prettyTree' l
prettyTree' :: (Show a) => BinTree a -> String
prettyTree' Empty = "\n"
prettyTree' (Node Empty x Empty) = " " ++ show x ++ "\n"
prettyTree' (Node Empty x r) = " " ++ prettyTree' r ++ " " ++ show x ++
"\n"
prettyTree' (Node l x Empty) = " " ++ show x ++ " " ++ "\n" ++
prettyTree' l
prettyTree' (Node l x r) = " " ++ prettyTree' r ++ " " ++ show x ++ "\n"
++ " " ++ prettyTree' l
I don't understand what I'm doing wrong. Any help would be greatly
appreciated.

No comments:

Post a Comment