非穷举模式匹配?



我有以下代码:

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指出,对于像FloatDouble这样的浮点数,情况并非如此(尽管严格来说,Ord对于浮点数的定义并没有定义顺序关系)。

您可以使用otherwise(这是True的别名),这意味着无论nnum如何关联都将"触发";最后的守卫;或者我们可以使用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

相关内容

  • 没有找到相关文章

最新更新