-1

我的功能是

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
4

1 回答 1

2

让我们尝试手动评估它几个步骤(没有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.

所以守卫中的所有测试都失败了,模式匹配x | ...失败了,报告为"non-exhaustive patterns".

在 GHCi 中:

> case False of True -> 1

*** Exception: <interactive>:789:1-23: Non-exhaustive patterns in case
于 2021-03-19T16:38:19.607 回答