S SmartDocs
Series: haskell haskell 34 lines · Updated 2026-02-03

DrawTree.hs

haskell/Week9/DrawTree.hs

module DrawTree(
    BinaryTree(Null, Node),
    printTree -- :: (Show a) => BinaryTree a -> IO ()
) where

{-
Module for drawing nice looking trees
David Quarel 13/02/2019

Don't worry too much about how this works,
or the types of these functions.
It's beyond the scope of this course.

Code modified from
http://hackage.haskell.org/package/containers-0.5.7.1/docs/src/Data.Tree.html#drawTree
-}

data BinaryTree a = Null | Node (BinaryTree a) a (BinaryTree a)
    deriving Show

printTree :: (Show a) => BinaryTree a -> IO ()
printTree = putStr.unlines.draw

draw :: (Show a) => BinaryTree a -> [String]
draw Null = ["Null"]
draw (Node left x right) = (show x) : drawSubTrees [right,left]
  where
    drawSubTrees [] = []
    drawSubTrees [t] =
        "|" : shift "`- " "   " (draw t)
    drawSubTrees (t:ts) =
        "|" : shift "+- " "|  " (draw t) ++ drawSubTrees ts

    shift first other = zipWith (++) (first : repeat other)

Related articles