'is there a way to define if a word has only the "a" vowel?
im trying to make a function on haskell, I know that the function is define like:
justWithA : [Char] -> Bool
justWithA [] = True
justWithA (x:xs) | (x == "a") = x + justWithA xs
| else (x == "e") = False
| else (x == "i") = False
| else (x == "o") = False
| else (x == "u") = False
I think there is a better way to define this function, just don't know the correct way to do it...
Solution 1:[1]
There are some problems with the current implementation:
- a guard does not use an
elsekeyword; xis aChar, so you compare withx == 'a', not;x == "a"x + justWithA xsmakes no sense sincexis aCharand you can not add aCharandBooltogether; and- your function will error if the string contains consonant, since these are not covered by any guard.
You can fix the function with:
justWithA : String -> Bool
justWithA [] = True
justWithA (x:xs)
| x == 'a' = justWithA xs
| x == 'e' = False
| x == 'i' = False
| x == 'o' = False
| x == 'u' = False
| otherwise = justWithA xs
we here only look for vowels and if there is a vowel that is e, i, o, or u, then we return False.
We can simplify this to:
justWithA :: String -> Bool
justWithA = all (`notElem` "eiou")
or if you want to take uppercase into account as well:
justWithA :: String -> Bool
justWithA = all (`notElem` "eiouEIOU")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Willem Van Onsem |
