0

I am trying to split a string in to a list of characters and removing any non-letters in the process. Here is my code so far:

getCharList :: String -> [String] 
getCharList x = [filter isLetter c | c <- splitOn "" x, c /= ""]

The output I receive from, for example:

getCharList "Why doesn't this work"

is:

["W","h","y","","d","o","e","s","n","","t","","t","h","i","s","","w","o","r","k"]

Could someone please explain why this doesn't seem to be able to remove the empty characters?

1 Answer 1

2

For your direct question: I will simply point out that filter isLetter c may be the empty list even when c is not the empty list; hence c /= "" does not ensure filter isLetter c /= "".

Popping up a level, I find your existing code to have a few oddities. The main thing you should realize is that String is exactly the same type as [Char] (it is just another name for it). There's no need to do any processing to convert a String into a list of its elements -- splitOn "" is basically unneeded work. The literal "foo" is just shorthand for the literal ['f', 'o', 'o'] (try them both in ghci!). I therefore propose a complete rewrite of your function, along the following lines:

getLetters :: String -> [Char]
getLetters = filter isLetter

(I used [Char] instead of String in the return type to emphasize that I intend to think of the returned thing as a list of letters rather than as a reasonable string. This is a human-level difference only; GHC would be just as happy to call the returned value a String.) This is perfectly idiomatic. If you prefer, you can also include the argument, writing instead:

getLetters s = filter isLetter s
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, the explanation really helped me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.