问题描述
我的功能是
import System.IO
import Debug.Trace
main :: IO ()
main = do
datei <- openFile "palindrom.txt" ReadMode
palin <- hGetContents datei
putStrLn $ unlines [ check x | x <- lines palin]
check :: String -> String
check x
| null x = ""
| trace ("call check "++ show x) False = x
| x == (reverse x) = if null x then ""
else do x ++ " Palindrom length " ++ show (length x)
我收到异常 Non-exhaustive patterns in the function `check`.
如何匹配字符串以完成模式,我也尝试了空字符串 ""
或者我什至无法在 Haskell 中的字符串上使用这种模式?
ps: palindrom.txt 是
a
aa
ab
aha
anna
anne
bry
bub
解决方法
让我们尝试手动评估几个步骤(没有 trace
调用),好吗?
check "ab"
===
case null "ab" of True -> ""
; _ -> case "ab" == (reverse "ab") of True ->
"ab" ++ " Palindrom length " ++ show (length "ab")
===
case False of True -> ""
; _ -> case "ab" == "ba" of True ->
"ab Palindrom length " ++ show 2
===
case "ab" == "ba" of True ->
"ab Palindrom length " ++ "2"
===
case False of True ->
"ab Palindrom length " ++ "2"
===
ERROR: none of the cases matched.
因此,guards 中的所有测试都失败了,x | ...
的模式匹配失败了,报告为 "non-exhaustive patterns"
。
在 GHCi 中:
> case False of True -> 1
*** Exception: <interactive>:789:1-23: Non-exhaustive patterns in case