所以我遇到了这个特殊的错误。在网上搜索但没有找到任何匹配项。奇怪的是,我不明白它怎么可能是非详尽无遗的。
下面是 cause 中的函数:
myand :: [Bool] -> Bool
myand (x:xs) | null (x:xs) = True
| null xs = x
| otherwise = x && myand xs
myor :: [Bool] -> Bool
myor (x:xs) | null(x:xs) = False
| null xs = x
| otherwise = x || myor xs
safetail :: [a] -> [a]
safetail (x:xs) |null (x:xs) = []
|otherwise = xs
这些是非常简单的函数,在文件中定义,当我尝试使用空列表运行它们时,它们都会生成异常。
运行示例:
*Main> myor [True]
True
*Main> myor []
*** Exception: tp2.hs:(10,1)-(12,38): Non-exhaustive patterns in function myor
*Main> myor [True, False, True]
True
最奇怪的部分是前两个昨天运行良好 - 如果“null (x:xs)”被“length (x:xs) == 0”替代,也会产生相同的错误。我还发现 null (x:xs) = True 适用于递归情况但不适用于纯空列表情况很有趣
最佳答案
重写这些以使用条件而不是守卫,我们得到
myand (x:xs) = if null (x:xs) then True
else if null xs then x
else x && myand xs
myor (x:xs) = if null(x:xs) then False
else if null xs then x
else x || myor xs
safetail (x:xs) = if null (x:xs) then []
else xs
很明显,每个定义只有一个子句,模式为x:xs
,并且x:xs
不匹配空列表。
(请注意,null (x:xs)
永远不会是 True
,因为 x:xs
是一个至少包含一个元素的列表。)
这些是你想要匹配的:
myand [] = True
myand [x] = x
myand (x:xs) = x && myand xs
myor [] = False
myor [x] = x
myor (x:xs) = x || myor xs
safetail [] = []
safetail (_:xs) = xs
另请注意,myand
和 myor
只需要两个子句。
当递归到达空列表时你的函数不会失败的原因是它没有到达它,由于你的“恰好一个元素”守卫,null xs
。
myand [] = True
myand (x:xs) = x && myand xs
myor [] = False
myor (x:xs) = x || myor xs
关于haskell - 详尽定义的功能中的非详尽模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74009329/