模式匹配不正确

发布于 2025-02-13 14:50:41 字数 901 浏览 1 评论 0 原文

我有点新手Haskell,

data Tree a = Leaf | Branch (Tree a) a (Tree a)
  deriving (Show, Eq)

insert :: (Ord a, Eq a) => a -> Tree a -> Tree a
insert x Leaf = Branch Leaf x Leaf
insert x (Branch l v r)
  | x <= v = Branch (insert x l) v r
  | x > v = Branch l v (insert x r)

代码会发出以下警告(但编译):

app\Main.hs:10:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for `insert':
        Patterns not matched:
            _ (Branch Leaf _ Leaf)
            _ (Branch Leaf _ (Branch _ _ _))
            _ (Branch (Branch _ _ _) _ Leaf)
            _ (Branch (Branch _ _ _) _ (Branch _ _ _))
   |
10 | insert x Leaf = Branch Leaf x Leaf
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...

从技术上讲 x&lt; = v x&gt; V 应该涵盖所有可能的替代方案,但是我有此警告。如果我在第二种情况下使用,我实际上是修复的,但是它不应该这样起作用吗?

I'm kinda new to haskell

data Tree a = Leaf | Branch (Tree a) a (Tree a)
  deriving (Show, Eq)

insert :: (Ord a, Eq a) => a -> Tree a -> Tree a
insert x Leaf = Branch Leaf x Leaf
insert x (Branch l v r)
  | x <= v = Branch (insert x l) v r
  | x > v = Branch l v (insert x r)

The code gives the following warning (but compiles):

app\Main.hs:10:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for `insert':
        Patterns not matched:
            _ (Branch Leaf _ Leaf)
            _ (Branch Leaf _ (Branch _ _ _))
            _ (Branch (Branch _ _ _) _ Leaf)
            _ (Branch (Branch _ _ _) _ (Branch _ _ _))
   |
10 | insert x Leaf = Branch Leaf x Leaf
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...

Technically speaking x <= v and x > v should cover all possible alternatives, but I'm having this warning. I's actually fixed if I use otherwise in the second case, but shouldn't it work just like this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

本王不退位尔等都是臣 2025-02-20 14:50:44

ord 实例应该定义总订单,但是Haskell无法执行这一要求,也无法检测到 ord od> ord 实例确实是总订单。

Prelude> data Foo = A | B deriving Eq
Prelude> instance Ord Foo where _ <= _ = False; _ > _ = False
Prelude> A <= B
False
Prelude> A > B
False

使用否则不起作用,因为它是 true (按字面定义,它是 x&lt; = v false ,但因为它是 true ,无论 x&lt; = v 是TRUE还是FALSE, 。知道&lt; = &gt; 每个 can 返回 true 不保证其中一个

An Ord instance should define a total order, but Haskell is unable to enforce that as a requirement nor is it able to detect if an Ord instance is, indeed, a total order.

Prelude> data Foo = A | B deriving Eq
Prelude> instance Ord Foo where _ <= _ = False; _ > _ = False
Prelude> A <= B
False
Prelude> A > B
False

Using otherwise works not because it is True (which it is, by literal definition) when x <= v is False, but because it is True regardless of whether x <= v is true or false. Knowing that <= and > each can return True does not guarantee that one of them will.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文