I want to create a tree from a file in Haskell. For that, i read the file into this list of lists:
The names in each element of the list follow this pattern:
["Name","Dad","Mum"]
[["Bob","Dylan","Susan"],
["Dylan","Cole","Sarah"],
["Cole","Patrick","Patricia"],
["Sarah","David","Fiona"],
["Susan","Michael","Madeline"]]
The desired output is something like:
Bob
Dylan
Cole
Patrick
Patricia
Sarah
David
Fiona
Susan
Michael
Madeline
The spaces could be a tab, i just put more to emphasise my point.
Here's what i've managed to do so far:
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
createTree :: (Ord a) => [a] -> Tree a
createTree [] = EmptyTree
createTree (x:xs) = createTree2 (Node x EmptyTree EmptyTree) xs
where
createTree2 tree [] = tree
createTree2 tree (y:ys) = createTree2 (treeInsert y tree) ys
printTree :: Show a => Tree a -> IO ()
printTree = (mapM_ putStrLn) . treeIndent
where
treeIndent EmptyTree = ["\nEmpty Tree\n"]
treeIndent (Node v lb rb) =
[(show v)] ++
map (" " ++) ls ++
("" ++ r) : map (" " ++) rs
where
(r:rs) = treeIndent $ rb
ls = treeIndent $ lb
All this lets me, very basically create the tree, and print it to the screen. What i'm struggling with is the proper creating of the tree according to this problem.