返回数据树中的分支Haskell

我正在尝试返回数据树中的分支。目前我的代码只返回第一个分支。

data DTree a = Leaf a | Branch a (DTree a) (DTree a) deriving (Show)
get_b :: DTree Int -> [Int]
get_branches (Branch x _ _) = [x]
get_branches (Branch _ l r)  = get_branches r ++ get_branches l

示例输出

ghci > get_branches (Branch 2 (Leaf 3) (Branch 1 (Leaf 9) (Leaf 5)))
[2]

回答

也许这就是你要找的东西?

get_branches :: DTree Int -> [Int]
get_branches (Branch x l r)  = [x] ++ get_branches r ++ get_branches l
get_branches (Leaf x) = [x]

您的函数没有基本情况。所以使用模式“叶子”。

此外,模式 (Branch x _ _) (Branch _ lr) 是相同的模式,除了 (Branch _ lr) 你得到左右分支。


以上是返回数据树中的分支Haskell的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>