Haskell-打印树数据:函数toList中的非穷举模式
我有一个由数据结构表示的Haskell-打印树数据:函数toList中的非穷举模式,haskell,tree,functional-programming,Haskell,Tree,Functional Programming,我有一个由数据结构表示的树: data Tree a = Node (Tree a) (Tree a)| Leaf a t1 :: Tree Int t1 = (Node (Node (Leaf 23) (Leaf 42)) (Node (Leaf 19) (Leaf 65))) 现在我需要打印树叶的数据: toList :: Tree a -> [a] toList (Node (Leaf a) (Leaf b)) = [a] ++ [b] toList (Node (L
树
:
data Tree a = Node (Tree a) (Tree a)| Leaf a
t1 :: Tree Int
t1 = (Node (Node (Leaf 23) (Leaf 42)) (Node (Leaf 19) (Leaf 65)))
现在我需要打印树叶的数据:
toList :: Tree a -> [a]
toList (Node (Leaf a) (Leaf b)) = [a] ++ [b]
toList (Node (Leaf a) (Node x y)) = [a] ++ (toList (Node x y))
toList (Node (Node x y) (Leaf b)) = (toList (Node x y)) ++ [b]
不幸的是,我不断地得到错误:
函数toList中的非穷举模式
然而,我使用括号
我做错了什么?这意味着你可以用一个值调用
toList
,并且你的所有行都将无法启动
当我使用两个节点调用脚本时,就是这种情况:toList(Node(Node x y)(Node z t))
。在这种情况下,所有线路都将失效。您可能需要添加以下行:
toList (Node (Node x y) (Node z t)) = (toList (Node x y))++(toList (Node x y))
或者再短一点:
toList (Node a@(Node _ _) b@(Node _ _)) = (toList a)++(toList b)
另一个是一个单个叶
:toList(叶x)
:
这是说你让事情变得过于复杂。您可以简单地使用两行:
toList :: Tree a -> [a]
toList (Leaf x) = [x]
toList (Node x y) = toList x ++ toList y
很容易看出,这里涵盖了所有情况,因为只有两个数据构造函数,并且我们没有对它们的参数设置模式约束。两个节点
s如何?启用带有-Wall
的警告将有1)在编译时而不是在运行时发出此信号,2)指出该情况这是不匹配的。强烈推荐。不,这是一个错误!当模式匹配无法找到匹配的案例时,GHCi在运行时打印的正是该案例。编译时警告读取“模式匹配是非穷举的”,运行时错误读取“函数中的非穷举模式”。
toList :: Tree a -> [a]
toList (Leaf x) = [x]
toList (Node x y) = toList x ++ toList y