Home > Mobile >  Return only the vowels in a list of strings
Return only the vowels in a list of strings

Time:11-14

I have to write the onlyVowels :: [[Char]] -> [[Char]] function that should only return the vowels.

For example: onlyVowels ["Return", "Only", "Vowels", "Please"] == ["eu", "Oy", "oe", "eae"]

So far, I have come up with this:

onlyVowels x = filter (isAVowel x) x where
  isAVowel x = elem x "aeiouyAEIOUY"

The problem with this is the fact that I have to check a list of words, not just a character. This exercise also prohibits the use of recursion.

CodePudding user response:

onlyVowels :: [[Char]] -> [[Char]]
onlyVowels = map (filter isAVowel) where
  isAVowel x = x `elem` "aeiouyAEIOUY"

Use map to apply your filtering function to each string in the list of strings. Also note that this is eta reduced. It is the same as writing:

onlyVowels xs = map (filter isAVowel) xs where...

Using toLower from Data.Char may also be a good idea. Then you can filter only on "aeiouy", like the following:

import Data.Char (toLower)

onlyVowels :: [[Char]] -> [[Char]]
onlyVowels = map (filter isAVowel) where
  isAVowel x = toLower x `elem` "aeiouy"
  • Related