Skip to content

Instantly share code, notes, and snippets.

@liubiantao
Last active August 29, 2015 14:15
Show Gist options
  • Save liubiantao/90d3b8ad1e441276af1d to your computer and use it in GitHub Desktop.
Save liubiantao/90d3b8ad1e441276af1d to your computer and use it in GitHub Desktop.
-- Custom implementation of 'show' for producing a more readable string
-- representation of BST's (convenient for debugging the 2nd CS4621 assignment).
-- The following data declaration is assumed:
--
-- data BST a = EmptyBST | Node (BST a) a (BST a)
--
-- *** I N S T R U C T I O N S ***
--
-- 1. Copy and paste the following lines at the bottom of your file 'BST.hs'.
-- 2. (Re)load 'BSTplus.hs' in GHCi.
-- 3. Try running
--
-- insert 4 $ insert 5 $ insert 3 emptyBST
--
-- in GHCi ('insert' is defined in 'BSTplus.hs'). The output should be
--
-- Node 3
-- EmptyBST
-- Node 5
-- Node 4
-- EmptyBST
-- EmptyBST
-- EmptyBST
-- make 'BST a' showable, under the condition that 'a' be showable
instance (Show a) => Show (BST a) where
show bst = pretty bst 0
-- pretty bst lvl : a string representation of BST 'bst',
-- with indentation level 'lvl'
pretty :: Show a => BST a -> Int -> String
pretty bst lvl =
let indent = take (lvl * tabsize) $ repeat ' '
tabsize = 3
in case bst of
EmptyBST -> indent ++ "EmptyBST\n"
Node lsub rootval rsub -> indent ++ "Node " ++ show rootval ++ "\n" ++
pretty lsub (lvl + 1) ++
pretty rsub (lvl + 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment