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"]
答案 0 :(得分:1)
我认为这样的事情应该有效:
branch :: Tree a b -> [[b]]
branch (Leaf _) = [[]]
branch (Branch (a, right) (b, left)) = map (a :) (branch right)
++ map (b :) (branch left)