简体   繁体   English

列举穿过玫瑰树Haskell的所有路径

[英]Enumerate all paths through a rose tree Haskell

I'm working with a version of a Tree of the type: 我正在使用以下类型的Tree:

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, ie if the tree was: 我的目标是得到一个返回对[(Event,[Int])]对的列表的函数,其中[Int]是每个Event的坐标(在树中到达它的路径),即如果树是:

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

Then I would want it to return [event,[0]] . 然后,我希望它返回[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. 然后,对于Split,需要在每个子树上递归地应用该函数。 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? 有任何想法吗?

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. 首先使用OP中的zip [1..]枚举xs的树。 We get a list of kind-of triples (n,(string,tree)) , and we do not need the string . 我们得到一个种类的三元组(n,(string,tree)) ,并且我们不需要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 . 对于任何这样的“三元组”,我们使用coords tree递归:这会生成[(event1, path1), (event2, path2), ...]形式的列表,其中路径相对于tree ,而不是Split str xs We need to add n in front of every path, so we finally generate (event, n:path) . 我们需要在每个路径前添加n ,因此我们最终生成(event, n:path)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM