我有一个由数据结构表示的tree

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,所有行都将无法触发。

当我用两个Node调用您的脚本时就是这种情况: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)


另一个是单个LeaftoList (Leaf x)

toList (Leaf x) = [x]


话虽这么说,您会使事情变得过于复杂。您可以简单地使用两行:

toList :: Tree a -> [a]
toList (Leaf x) = [x]
toList (Node x y) = toList x ++ toList y


很容易看到这里涵盖了所有情况,因为只有两个数据构造函数,我们没有在它们的参数上加上模式约束。

关于haskell - Haskell-打印树数据:toList函数中的非穷尽模式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42510345/

10-11 22:35
查看更多