You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell非列表场景出现Pattern match非穷尽警告的原因及解决

警告触发原因

Pattern match(es) are non-exhaustive 警告并非仅在列表场景下出现,只要函数分支(包括模式匹配、守卫条件)没有覆盖所有可能的输入情况,编译器就会触发该警告。

针对你写的 teste 函数,四个守卫条件存在未覆盖的输入场景:当满足 ord (toUpper a) == ord (toUpper b) 且 ord a == ord (toUpper b) 时,四个条件全部不匹配。比如输入 a='A'、b='A' 时:

  • 前两个守卫判断 ord(toUpper a) 和 ord(toUpper b) 的大小,二者相等所以不触发
  • 后两个守卫判断 ord a 和 ord(toUpper b) 的大小,二者也相等所以不触发

此时函数没有对应返回逻辑,因此编译器会抛出警告,提示 _ _(即任意两个Char参数)存在未匹配的情况。

修复方案

你只需要补全所有分支的覆盖即可,最简单的方式是在守卫末尾加一个 otherwise 兜底分支,覆盖所有剩余的情况,根据你的业务需求指定对应返回值即可,示例如下:

import Data.Char (ord, toUpper)

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 -- 这里替换为你需要的返回值即可

你后续修改的 alphabetOrder 函数没有该警告是合理的:compare 函数的返回值只有 LT、GT、EQ 三种,你的case分支已经完整覆盖了所有三种可能的返回结果,不存在遗漏的情况,因此不会触发非穷尽匹配警告。

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

内容的提问来源于stack exchange,提问作者user15277323

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 14:36:03