我有以下代码:
data Tree = Leaf | Node Int Tree Tree
deriving (Eq, Show, Read, Ord)
insert :: Int -> Tree -> Tree
insert n Leaf = Node n Leaf Leaf
insert n tree@(Node num lt rt)
| n < num = Node num (insert n lt) rt
| n > num = Node num lt (insert n rt)
| n == num = tree
对我来说,insert
函数似乎是详尽的可能的参数模式,但当我试图用ghc编译时,它说
Pattern match(es) are non-exhaustive In an equation for ‘insert’: Patterns not matched: _ (Node _ Leaf Leaf) _ (Node _ Leaf (Node _ _ _)) _ (Node _ (Node _ _ _) Leaf) _ (Node _ (Node _ _ _) (Node _ _ _))
你能告诉我为什么吗?
Haskell不知道如果n < num
不成立,n > num
不成立,那么n == num
成立。@Noughtmare指出,对于像Float
和Double
这样的浮点数,情况并非如此(尽管严格来说,Ord
对于浮点数的定义并没有定义顺序关系)。
您可以使用otherwise
(这是True
的别名),这意味着无论n
和num
如何关联都将"触发";最后的守卫;或者我们可以使用compare
并详尽地定义所有情况:
insert :: Int -> Tree -> Tree
insert n Leaf = Node n Leaf Leaf
insert n tree@(Node num lt rt) = go (compare n num)
where go LT = Node num (insert n lt) rt
go GT = Node num lt (insert n rt)
go EQ = tree