尝试在两个字符串中查找第一个不同字符时出现非详尽模式错误

Non-exhaustive patterns error when trying to find the first different character in two strings

我想编写一个 match :: String -> String -> Maybe Char 函数,它应该 return 第一个字符串的不同字符(例如 Just 'b')。如果两个字符串相同或第一个字符串是第二个字符串的前缀,函数应该 return Nothing.

到目前为止,我有这个代码:

match :: String -> String -> Maybe Char
match [] [] = Nothing
match [x] [] = Just x
match [] [y] = Nothing
match [x] [y]
  | x == y = Nothing 
  | otherwise = Just x
match (x:xs) (y:ys)
  | x == y = match xs ys
  | otherwise = Just x

哪个 return 是正确的值,比方说 match "apple" "aple" == Just 'p',但对于下面的情况,我得到一个 Non-exhaustive patterns 错误,这很奇怪,因为我认为我已经涵盖所有案例:

*main> match (replicate 21 'a') (repeat 'a')
*** Exception: match.hs:(64,1)-(72,22): Non-exhaustive patterns in function match

与单例列表([x]恰好一个元素的列表)在这里是没有必要的。您可以使用空列表 [] 和“缺点”(x:xs):

match :: String -> String -> Maybe Char
match <strong>[] _</strong> = Nothing
match <strong>(x:_) []</strong> = Just <strong>x</strong>
match (x:xs) (y:ys)
  | x == y = match xs ys
  | otherwise = Just x