Starting from a list of “tree paths”, for example:
[["a", "b", "c"], ["a", "b", "e"], ["f", "g"]]
I would like to build a forest ([Tree]
):
a
|_ b
|_ c
|_ e
f
|_ g
This is my attempt so far. I have been constructing the building blocks in order to assemble the final solution:
module Main where
import Data.Tree
insertPath :: Eq a => [a] -> [Tree a] -> [Tree a]
insertPath [] ts = ts
insertPath (y:ys) [] = Node y [] : []
insertPath (y:ys) ((Node x ts):ts')
| y /= x = Node x ts : insertPath ys ts'
| otherwise = Node x (insertSubTrees ys ts) : insertPath ys ts'
insertSubTrees :: Eq a => [a] -> [Tree a] -> [Tree a]
insertSubTrees [] ts = ts
insertSubTrees (y:ys) [] = insertSubTrees ys [Node y []]
insertSubTrees (y:ys) (t:ts) = undefined
My questions are:
- Should I define functions over a
Tree
or a list ofTree
? - Is my approach sensible ? What are other alternatives ?
- How can I develop a
buildForest :: Eq a => [a] -> [Tree a] -> [Tree a]
function ?