繁体   English   中英

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

[英]Enumerate all paths through a rose tree Haskell

我正在使用以下类型的Tree:

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

我的目标是得到一个返回对[(Event,[Int])]对的列表的函数,其中[Int]是每个Event的坐标(在树中到达它的路径),即如果树是:

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

然后,我希望它返回[event,[0]] 我想忽略树的任何空头。

所以我的功能看起来像

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

然后,对于Split,需要在每个子树上递归地应用该函数。 我想到了:

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

但这会给我嵌套任意长度的嵌套列表,还有其他一些问题。 有任何想法吗?

可能的解决方案可能是:

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

首先使用OP中的zip [1..]枚举xs的树。 我们得到一个种类的三元组(n,(string,tree)) ,并且我们不需要string 对于任何这样的“三元组”,我们使用coords tree递归:这会生成[(event1, path1), (event2, path2), ...]形式的列表,其中路径相对于tree ,而不是Split str xs 我们需要在每个路径前添加n ,因此我们最终生成(event, n:path)

暂无
暂无

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

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