[英]General Tree in Haskell = Rose Tree? Postoder for a rose tree?
I was supposed to create a data structure for a Tree, where every Node has an undefined amount of branches. 我应该为Tree创建一个数据结构,其中每个Node都有未定义数量的分支。 I am guessing this will be a rose tree.
我猜这将是一棵玫瑰树。
data GTree a = Node a [GTree a]
Now I am supposed to write a postorderG function that will give me a list of all my elements in my general in a postorder sequence I wrote this but it does not seem right... Could someone help me? 现在,我应该编写一个postorderG函数,该函数将按照我编写的后序顺序为我提供通用中所有元素的列表,但这似乎不正确……有人可以帮我吗?
postorderG :: GTree a -> [a]
postorderG (Node x l r) = postorder l ++ postorder r ++ [GTree x]
GTree
is a type constructor, not a data constructor; GTree
是类型构造函数,而不是数据构造函数; a tree would be created with Node x []
, not GTree x
. 将使用
Node x []
而不是GTree x
创建树。
However , you don't need to create a tree at all here. 但是 ,您根本不需要在此处创建树。 You just need a the value stored at the root of the input tree for the final list in the return value.
您只需要将一个值存储在输入树的根目录中,以作为返回值中的最终列表。
postorderG :: GTree a -> [a]
postorderG (Node x ch) = concatMap postorderG ch -- [a]
++ [x] -- [a], not [GTree a]
If you wanted to, you could create a singleton tree to append to ch
, the apply postOrderG
to each child and the new singleton in order. 如果愿意,您可以创建一个单例树以附加到
ch
,将postOrderG
应用于每个子级,并按顺序将新的单例应用到。
postorderG (Node x ch) = concatMap postorderG (ch ++ [Node x []])
Taking advantage of the []
monad instead of using concatMap
, the RHS would look like either 利用
[]
monad而不是使用concatMap
,RHS看起来像
(ch >>= postorderG) ++ [x]
or 要么
(ch ++ [Node x []]) >>= postorderG
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.