【发布时间】:2014-05-20 21:53:45
【问题描述】:
Haskell 中的树有问题。有一棵树:
data Tree a b = Leaf a | Branch (b,Tree a b) (b,Tree a b)
deriving(Eq, Show)
tree = Branch
("A",Branch
("C",Leaf 3)
("D",Branch
("G",Leaf 7)
("H",Leaf 6)
)
)
("B",Branch
("E",Leaf 5)
("F",Leaf 4)
)
我需要定义一个函数,它返回这个树中所有分支的列表,输出是这样的:[["A", "C"], ["A", "D", "G"],["A","D","H"],["B","E"],["B","F"]]。我做错了,但不知道如何解决:
branch:: Tree a b -> [[b]]
branch (Leaf x) = []
branch (Branch (a,right) (b,left)) = ([y] ++ branch left) ++ ([b] ++ branch right)
我得到的输出是["A","C","D","G","H","B","E","F"]
【问题讨论】:
-
目前您的
branch函数只返回所有节点的列表。
标签: haskell tree tree-traversal