模式匹配在 Haskell 函数中并不详尽

我在 Haskell 中阅读了有关此警告的类似问题,但这些问题通常涉及列表,而我的则没有:

teste :: Char -> Char -> Int
teste a b
   |ord (toUpper a) < ord (toUpper b) = 1
   |ord (toUpper a) > ord (toUpper b) = 2
   |ord a > ord (toUpper b) = 3
   |ord a < ord (toUpper b) = 4

为什么出现“模式匹配”警告?

Pattern match(es) are non-exhaustive
In an equation for `teste': Patterns not matched: _ _

有什么我可以做的吗?

编辑:新函数的代码:

alphabetOrder :: Char -> Char -> Char 
alphabetOrder a b =  case compare (toUpper a) (toUpper b) of LT -> a; GT -> b; EQ -> a

回答

结果应该是什么时候ord a == ord (toUpper b)?你没有具体说明,这是一个真正的可能性。

不过,即使你没有指定,编译器仍然不能告诉><以及==涵盖所有可能的情况。对于编译器,>, <, 和==只是一些函数,不能证明其中之一总是返回True

所以你真正需要做的是添加一个当没有其他案例匹配时将匹配的案例:

teste :: Char -> Char -> Int
teste a b
|ord (toUpper a) < ord (toUpper b) = 1
|ord (toUpper a) > ord (toUpper b) = 2
|ord a > ord (toUpper b) = 3
|ord a < ord (toUpper b) = 4
|otherwise = 5
  • 另一种选择:编译器无法判断`&lt;`、`&gt;` 和`==` 覆盖了所有可能的情况,但它能够判断出`LT`、`EQ` 和`GT` 覆盖所有可能的情况。`teste ab = case compare (ord (toUpper a)) (ord (toUpper b)) of LT -&gt; 1; GT -&gt; 2; EQ -&gt; case compare (ord a) (ord (toUpper b)) of LT -&gt; 3; GT -&gt; 4; 情商 -&gt; 5`。
  • 或者同样的事情只是一个 case 表达式,通过匹配两个比较的元组。`teste ab = case (compare (toUpper a) (toUpper b), compare a (toUpper b)) of (LT, _) -&gt; 1; (GT, _) -&gt; 2; (EQ, LT) -&gt; 3; (EQ, GT) -&gt; 4; (均衡器,均衡器)-&gt; 5`

以上是模式匹配在 Haskell 函数中并不详尽的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>