3

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:

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

1 Answers1

3

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
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555