Home > Software engineering >  I keep getting a Non-exhaustive patterns error
I keep getting a Non-exhaustive patterns error

Time:11-23

I've tested my code on Jupyter where it works fine, but for some reason in Haskell I get some sort of error

getCount :: String -> Int
getCount (x:xs) = sum[ 1 |c<- (x:xs), check c]
                      where check :: Char -> Bool
                            check v = any(v==)['a','o','e','i','u']

Error

uncaught exception: PatternMatchFail
src/Codewars/Kata/Vowel.hs:(4,1)-(6,67): Non-exhaustive patterns in function getCount

(after 1 test)
  0

enter image description here

CodePudding user response:

The (x:xs) pattern does not match the empty string (list). You do not need to pattern match, you can work with:

getCount :: String -> Int
getCount xs = sum [ 1 | c<- xs, check c]
                      where check :: Char -> Bool
                            check v = `any (v ==) ['a','o','e','i','u']

You can simplify this to:

getCount :: String -> Int
getCount xs = sum [ 1 | c<- xs, c `elem` "aeiou"]

or even work with filter:

getCount :: String -> Int
getCount = length . filter (`elem` "aeiou")
  • Related