title: Show Tree Haskell
body: <p>Consider the following data type</p>
  
  <pre><code>data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a
  </code></pre>
  
  <p>I'm trying to define an instance of Show (without importing any modules or using deriving) that would display the tree like so</p>
  
  <pre><code>Main*&gt; let a = Branch "x" (Branch "y" (Leaf 4) (Leaf 7)) (Leaf 9)
  Main*&gt; a
  "x"
       "y"
            4
            7
       9
  </code></pre>
  
  <p>So far, this is what I've come up with</p>
  
  <pre><code>findDepth (Leaf a) = 0
  findDepth (Branch a (b) (c)) = 1 + (max (findDepth b) (findDepth c))
  data Tree a b = Branch b (Tree a b) (Tree a b) | Leaf a
  instance (Show a, Show b) =&gt; Show (Tree a b) where
       show (Leaf x) = show x
       show (Branch a (b) (c)) =
            show a ++ "\n" ++ s2 ++ show b ++ "\n" ++ s2 ++ show c ++ "\n" ++ s1
                 where
                      d = findDepth (Branch a (b) (c))
                      s1 = addSpace (d-1)
                      s2 = addSpace d
                      addSpace n = replicate n '\t'
  </code></pre>
  
  <p>Unfortunately, this indents the nodes with the lowest depth the most and the highest depth nodes the least. I know that the findDepth function should actually be giving leaf the greatest value and branch the lowest value, but can't figure out a way to write the function recursively for both arguments. Any suggestions?</p>