Nicely printing/showing a binary tree in Haskell

Posted by nicole on Stack Overflow See other posts from Stack Overflow or by nicole
Published on 2012-09-23T21:34:28Z Indexed on 2012/09/23 21:37 UTC
Read the original article Hit count: 278

Filed under:
|
|
|

I have a tree data type:

data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a

...and I need to make it an instance of Show, without using deriving. I have found that nicely displaying a little branch with two leaves is easy:

instance (Show a, Show b) => Show (Tree a b) where
   show (Leaf x) = show x
   show (Branch val l r) = " " ++ show val ++ "\n" ++ show l ++ "  " ++ show r

But how can I extend a nice structure to a tree of arbitrary size? It seems like determining the spacing would require me to know just how many leaves will be at the very bottom (or maybe just how many leaves there are in total) so that I can allocate all the space I need there and just work 'up.' I would probably need to call a size function. I can see this being workable, but is that making it harder than it is?

© Stack Overflow or respective owner

Related posts about haskell

Related posts about tree