Enumerate all paths through a rose tree Haskell

475 views Asked by At

I'm working with a version of a Tree of the type:

Tree = Empty | Leaf Event | Split String [(String, Tree)]

My aim is to get a function that returns a list of pairs [(Event,[Int])] with [Int] being the coordinates (the path taken in the tree to reach it) of each Event, i.e if the tree was:

Split str [(str2, Leaf event), (str3, Empty)]

Then I would want it to return [event,[0]]. I want to ignore any empty ends to the tree.

so my function looks like

coords :: Tree -> [(Event,[Int])]
coords Empty = []
coords (Leaf event) = [event, []]

Then for Split it needs to recursively apply the function on each subtree. I thought of doing:

coords Split str xs = zip (coords trees) [1..] where
    trees = [snd(str,tree) | (str,tree) <-xs]

But this would give me nested lists of arbitrary length, among a couple of other problems. Any ideas?

1

There are 1 answers

4
chi On

A possible solution could be:

coords (Split _ xs) = [ (event, n:path)
      | (n,(_,tree)) <- zip [1..] xs 
      , (event, path) <- coords tree  ]

This starts by enumerating the trees in xs, using zip [1..] as done in the OP. We get a list of kind-of triples (n,(string,tree)), and we do not need the string. For any such "triple", we recurse with coords tree: this produces a list of the form [(event1, path1), (event2, path2), ...] where the paths are relative to tree, not to Split str xs. We need to add n in front of every path, so we finally generate (event, n:path).