Attila Fodor
Attila Fodor

Reputation: 27

String contains only the alphabet in haskell

I want to make a functions which decides wheter the character is a letter in the alphabet in Haskell

isLetter :: Char -> Bool

So the outcome may look like this: if I type isLetter 'c', the outcome will be True, and if it's isLetter ' ', then the outcome is False.

Upvotes: 2

Views: 5161

Answers (4)

Juan Carlos Ramirez
Juan Carlos Ramirez

Reputation: 11

We can use the elem function and ranges to see if a character is a letter or not. Notice that the range ['a'..'z'] contains all the letters from a to z in a list. Likewise, the range ['A'..'Z']is a list that contains all the uppercase letters. So, the function will check if the given character belongs to any of these lists and if it does, it returns True; otherwise, it returns False.

isLetter :: Char -> Bool
isLetter character = if character `elem` ['a'..'z'] || character `elem` ['A'..'Z']
                     then True
                     else False

Upvotes: 0

Alstonomy
Alstonomy

Reputation: 11

I think this will work for you.

isLetter :: Char -> Bool
isLetter c = (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'))

Upvotes: 1

sshine
sshine

Reputation: 16125

You can define this function yourself,

isLetter :: Char -> Bool
isLetter 'A' = True
isLetter 'B' = True
...
isLetter 'Z' = True

But what about lowercase letters? What about foreign letters like 'ß', 'ü', 'Ф', 'Й' or 'Æ' and their uppercase/lowercase variants? Because Unicode is so complex, for any production-level use you should depend on already built library functions. When you don't know what they're called, go to Hoogle and search for "Char -> Bool" and you'll often be pointed to a library that contains exactly what you want. :-)

For example, the documentation for Data.Char.isAlpha says:

Selects alphabetic Unicode characters (lower-case, upper-case and title-case letters, plus letters of caseless scripts and modifiers letters). This function is equivalent to Data.Char.isLetter.

I bet you didn't think of title-case letters, letters of caseless scripts and modifier letters! (I didn't.)

I didn't even know modifier letters existed. Apparently, 'ˀ' (glottal stop) is a letter used by the Squamish people of southwestern British Columbia, Canada. There are Canadian road signs out there that your function isn't taking into account!

Are you gonna be the guy who tells Ḇøᵇ that he can't get on the plane?! :Đ

Upvotes: 9

talex
talex

Reputation: 20544

You can use Data.Char.isAlpha to check that character is alphabet symbol.

Upvotes: 4

Related Questions