gpt4 book ai didi

haskell - 如何构建树中所有分支的列表?

转载 作者:行者123 更新时间:2023-12-02 03:35:25 24 4
gpt4 key购买 nike

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 :: Tree a b -> [[b]]
branch (Leaf _) = [[]]
branch (Branch (a, right) (b, left)) = map (a :) (branch right)
++ map (b :) (branch left)

关于haskell - 如何构建树中所有分支的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23761474/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com