0

我有以下代码:

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函数似乎是详尽的 wrt 可能的参数模式,但是当我尝试用 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 _ _ _)) 

你能帮我看看为什么吗?

4

1 回答 1

4

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
于 2021-09-15T17:14:19.797 回答