Generate all 3 letter words at least with 1 vowel in haskell

Viewed 177

I need to generate all 3 letter words at least with 1 vowel. I have already made a code to generate all words with 3 letters but I can't find how out to make every word with 1 vowel or more. This is my code:

alfabeto = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
alfabeto2 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
alfabeto3 = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

small = [alfabeto ++ alfabeto2 ++ alfabeto3 | alfabeto <- alfabeto, alfabeto2 <- alfabeto2, alfabeto3 <- alfabeto3]
1 Answers

We can define two alfabets, one with only vowels, and one with all characters:

vowels :: [Char]
vowels = "aeiouy"

letters :: [Char]
letters = [ 'a' .. 'z' ]

now for the result, the two first characters can be chosen both from the letters list, since regardless what we choose, for the last character we can pick a vowel of both are not vowels.

We thus can define a function that, given the first two characters, returns a list of vowels (if both characters are not vowels), or a list of letters (if at least one of the characters is a vowel). That function looks like:

pickThird :: Char -> Char -> [Char]
pickThird la lb
    | … = letters
    | otherwise = vowels

where you still need to fill in the … part.

Now we can use this in a list comprehension that looks like:

words3 :: [String]
words3 = [ [la, lb, lc] | la <- letters, lb <- letters, lc <- pickThird la lb ]

the pickThird will thus, depending on the choices of la and lb either return a list of all letters, or only the vowels.

Related