Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

I want to write a match :: String -> String -> Maybe Char function that should return the first string’s different character (e.g. Just 'b'). If both strings are identical or the first string is the second string’s prefix, the function should return Nothing.

So far, I have this code:

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

Which returns the correct value for, let’s say match "apple" "aple" == Just 'p', but for the case below, I get a Non-exhaustive patterns error, which is strange becuase I thought I’ve covered every case:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Matching with a singleton list ([x], a list with exactly one element) here is not necessary. You can work with the empty list [] and the "cons" (x:xs):

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading