0

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?

Adam
  • 5,403
  • 6
  • 31
  • 38
D.Dog
  • 21
  • 3

1 Answers1

2

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).

chi
  • 111,837
  • 3
  • 133
  • 218
  • 1
    Two details: (1) You need an extra `concat` on the outside, or to change the comprehension to `[addN cs {- etc. -} cs <- coords tree {- etc. -}]` (2) Given the usage example in the OP, the indexing should start from `0`. – duplode Mar 20 '18 at 17:14
  • @duplode (1) Right! I chose your second solution, and inlined `addN`. (2) I am unsure about starting from 0 since the OP used `zip (...) [1..]`. – chi Mar 20 '18 at 18:38
  • On (2), indeed -- the question is inconsistent on that point, so there isn't much we can do about it. – duplode Mar 20 '18 at 18:48
  • @duplode yes, It should really be [0..]. That was poorly thought out. – D.Dog Mar 21 '18 at 20:14