I've just started learning Haskell and I'm a bit stuck.
https://gyazo.com/b70aee3b5a031a6d65ea2fe993ea0824
I've made an attempt at it and I don't really know how to get my head around where I'm going wrong.
vowels :: String -> String
vowels [] = []
vowels xs = [] == [ x | x <- vowels , x == "a" || x == "e" || x == "i" || x == "o" || x == "u" ]
you're almost there
vowels xs = [ x | x <- xs , x == 'a' ||
x == 'e' ||
x == 'i' ||
x == 'o' ||
x == 'u' ]
String litterals are surrounded by " where Char litterals have ' and internally Strings in Haskell are just [Char] so you need to use characters.But haskell is known for conciseness and expressivity - list comprehensions are a nice way but can we do better?
What you actually, do is implement a filter, so let us analyze what you are filtering - vowels, so let us extract that part:
isVowel x = x == 'a' || ... || x == 'u'
well this is still not elegant, but there is a function called elem that checks whether something is contained in a list.
isVowel x = x `elem` ['a','e','i','o','u']
and knowing that String = [Char] we can rewrite that (using so called backtick-syntax which allows to use functions of 2 parameters as an infix function)
isVowel :: Char -> Bool
isVowel x = x `elem` "aeiou"
then coming back to the original problem now that we have a function telling us what a vowel is...
vowel :: String -> String
vowel = filter isVowel
now you might be interested where is the xs - well since haskell has a great type system it can derive that there is one parameter missing on both sides of the = sign, you don't need to write that yourself (this style is called pointfree).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With