我正在尝试将树减少为列表,但是我被困在这里..任何建议,我们感激不尽。
data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show)
treeToList :: (Ord a) => Tree a -> [a]
treeToList (Node root left right) = treeToList left ++ [root] ++ treeToList right
预期结果:
ghci> treeToList (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5)))
[1,2,3,4,5]
最佳答案
您有两个错误:
非穷尽模式(用于Leaf
构造函数)。
在Node
的模式中,您将root
匹配为左树值(Tree a
)而不是a
。
因此结果应如下所示:
data Tree a = Leaf a | Node (Tree a) a (Tree a) deriving (Eq, Show)
treeToList :: (Ord a) => Tree a -> [a]
treeToList (Leaf v) = [v]
treeToList (Node left root right) = treeToList left ++ [root] ++ treeToList right
*Main> treeToList (Node (Leaf 1) 2 (Node (Leaf 3) 4 (Leaf 5)))
[1,2,3,4,5]
关于haskell - 将树还原为haskell中的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33815735/