Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Vowels from a String and printing them in Haskell

Tags:

haskell

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" ]
like image 684
Fergus2k8 Avatar asked Dec 04 '25 21:12

Fergus2k8


1 Answers

First of all

you're almost there

vowels xs = [ x | x <- xs , x == 'a' ||
                            x == 'e' ||
                            x == 'i' ||
                            x == 'o' ||
                            x == 'u' ]

But what is the actual error?

  1. you were using the function as an input to your list
  2. 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?

yes we can!

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).

like image 130
epsilonhalbe Avatar answered Dec 06 '25 20:12

epsilonhalbe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!