【问题标题】:General Tree in Haskell = Rose Tree? Postoder for a rose tree?Haskell 中的通用树 = 玫瑰树?玫瑰树的海报?
【发布时间】:2018-08-11 12:54:39
【问题描述】:

我应该为树创建一个数据结构,其中每个节点都有未定义数量的分支。我猜这将是一棵玫瑰树。

data GTree a = Node a [GTree a] 

现在我应该编写一个 postorderG 函数,它会在后序序列中为我提供我将军中所有元素的列表 我写了这个,但它似乎不对...有人可以帮助我吗?

postorderG :: GTree a -> [a]
postorderG (Node x l r) = postorder l ++ postorder r ++ [GTree x]

【问题讨论】:

  • Node 构造函数只有两个参数,所以你的解构看起来像postorderG (Node x children)。我建议您查看concatMap 并注意postorderG 具有第一个参数所需的类型。

标签: haskell tree postorder


【解决方案1】:

GTreetype 构造函数,而不是数据构造函数;将使用Node x [] 而不是GTree x 创建一棵树。

然而,您根本不需要在这里创建树。您只需要一个存储在输入树根部的 value 即可作为返回值中的最终列表。

postorderG :: GTree a -> [a]
postorderG (Node x ch) =  concatMap postorderG ch -- [a]
                          ++ [x]         -- [a], not [GTree a]

如果您愿意,您可以创建一个单例树以附加到ch,将postOrderG 应用到每个孩子,然后按顺序创建新的单例。

postorderG (Node x ch) = concatMap postorderG (ch ++ [Node x []])

利用[] monad 而不是使用concatMap,RHS 看起来像

(ch >>= postorderG) ++ [x]

(ch ++ [Node x []]) >>= postorderG

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-04
    相关资源
    最近更新 更多