Skip to content

Instantly share code, notes, and snippets.

@phipsgabler
Created December 23, 2015 21:16
Show Gist options
  • Save phipsgabler/cec54781ff11f38911d5 to your computer and use it in GitHub Desktop.
Save phipsgabler/cec54781ff11f38911d5 to your computer and use it in GitHub Desktop.
Creating preorder tree by folding list
data Tree a = Leaf | Branch a (Tree a) (Tree a) deriving Show
insertLeftBalanced :: a -> Tree a -> Tree a
insertLeftBalanced x Leaf = Branch x Leaf Leaf
insertLeftBalanced x (Branch m Leaf r) = Branch m (Branch x Leaf Leaf) r
insertLeftBalanced x (Branch m l Leaf) = Branch m l (Branch x Leaf Leaf)
insertLeftBalanced x (Branch m l r) = Branch m (insertLeftBalanced x l) r
listToTree :: [a] -> Tree a
listToTree xs = foldl (flip insertLeftBalanced) Leaf xs
-- cf. http://stackoverflow.com/a/19083798/1346276
indent :: [String] -> [String]
indent = map (" "++)
layoutTree :: Show a => Tree a -> [String]
layoutTree Leaf = [] -- wow, that was easy
layoutTree (Branch here left right)
= indent (layoutTree right) ++ [show here] ++ indent (layoutTree left)
prettyTree :: Show a => Tree a -> String
prettyTree = unlines . layoutTree
printTree :: Show a => Tree a -> IO ()
printTree = putStrLn . prettyTree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment