1

My Function is

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)

I get the Exception Non-exhaustive patterns in the function `check`.

How can I match the string to complete the pattern, I tried also the empty String "" or I am even not able to use this kind of pattern on a String in Haskell?

ps: The palindrom.txt is

a
aa
ab
aha
anna
anne
bry
bub
Will Ness
  • 70,110
  • 9
  • 98
  • 181
logn
  • 113
  • 4
  • 3
    The code doesn't compile (and the compilation error is not the error message mentioned). Please post a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Mark Seemann Mar 19 '21 at 12:03
  • 3
    What if all your guards are false? If you write multiple guards, and the last one is not equivalent to `otherwise` (i.e. it is always true), then your code does not cover all the cases. Also it's weird to check `null x` in a guard and then write `if null x` after that, since the latter check is trivially false at that point. – chi Mar 19 '21 at 12:09
  • Its becouse of the data i changed it to datei now it should compile, And the reason why i wrote the if statement is, i didnt know where the problem with the empty string is, so i just tried because i get an output for the first lines of palindrome.txt then its stops. – logn Mar 19 '21 at 12:19
  • 1
    What makes you think the empty string is the thing causing the problem? (Hint: it's not.) – Daniel Wagner Mar 19 '21 at 15:51
  • What do you expect your function to do if the input string is *not* a palindrome? – Jon Purdy Mar 19 '21 at 20:13

1 Answers1

2

Let's try evaluating it by hand for a few steps (sans the trace call), shall we?

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.

So all the tests in guards having failed, the pattern match for x | ... fails a well, which is reported as "non-exhaustive patterns".

In GHCi:

> case False of True -> 1

*** Exception: <interactive>:789:1-23: Non-exhaustive patterns in case
Will Ness
  • 70,110
  • 9
  • 98
  • 181