【问题标题】:Enumerate all paths through a rose tree Haskell枚举通过玫瑰树 Haskell 的所有路径
【发布时间】:2018-08-29 07:23:18
【问题描述】:

我正在使用以下类型的树的一个版本:

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

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

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

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

所以我的函数看起来像

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

然后对于拆分,它需要递归地将函数应用于每个子树。我想这样做:

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

但这会给我提供任意长度的嵌套列表,以及其他几个问题。有什么想法吗?

【问题讨论】:

    标签: haskell recursion functional-programming tree multiway-tree


    【解决方案1】:

    可能的解决方案是:

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

    首先使用zip [1..] 枚举xs 中的树,就像在OP 中所做的那样。我们得到了一个三元组列表(n,(string,tree)),我们不需要string。对于任何这样的“三元组”,我们使用coords tree 进行递归:这会生成[(event1, path1), (event2, path2), ...] 形式的列表,其中路径相对于tree,而不是Split str xs。我们需要在每条路径前面加上n,所以我们最终生成(event, n:path)

    【讨论】:

    • 两个细节:(1)你需要一个额外的concat在外面,或者将理解更改为[addN cs {- etc. -} cs &lt;- coords tree {- etc. -}](2)给定OP中的使用示例,索引应该从0.
    • @duplode (1) 对!我选择了您的第二个解决方案,并内联了addN。 (2)我不确定从0开始,因为OP使用了zip (...) [1..]
    • 在 (2) 上,确实——问题在这一点上是不一致的,所以我们无能为力。
    • @duplode 是的,它应该是 [0..]。考虑不周。
    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 2015-10-21
    • 1970-01-01
    相关资源
    最近更新 更多