Removing special characters from a list of strings Haskell

Viewed 199

I have a list of strings

["This!","i2s","a","li!st","of","strings"]

And I want to make a function such that it removes all the special characters from individual strings

["This", "is", "a", "list", "of", "strings"]

I made a function like this(I'm only considering ! as special characters for now):

removeUglyCharacters []=[]
removeUglyCharacters (x:xs) | x == "!"  = removeUglyCharacters xs
                            | otherwise = x:removeUglyCharacters xs

However, if I understand correctly, this will check if one string is an exclamation and then continue.

*Main> let abc = ["this","wont","work","as!","intended","!"]
*Main> removeUglyCharacters abc
["this","wont","work","as!","intended"]

It will not check every character in a string and remove the exclamation. I just can't seem to figure out how to do this. I was thinking along the lines of needing a pattern match for every individual string too?

1 Answers

You should first make a function to remove '!' from a single string. The only thing that you have to change for that is replacing "!" with '!':

removeUglyCharacters :: String -> String
removeUglyCharacters [] = []
removeUglyCharacters (x:xs) | x == '!'  = removeUglyCharacters xs
                            | otherwise = x:removeUglyCharacters xs

Then you can make a mapping where you map each string with the removeUglyCharacters:

removeFromListOfStrings :: [String] -> [String]
removeFromListOfStrings = map removeUglyCharacters

Your removeUglyCharacters can be replaced with a filter ('!' /=), so that means that we can work with:

removeFromListOfStrings :: [String] -> [String]
removeFromListOfStrings = map (filter ('!' /=))

You can limit the filtering further to only allow characters in the A-Z a-z range. For example with:

import Data.Char(isAsciiLower, isAsciiUpper)

removeFromListOfStrings :: [String] -> [String]
removeFromListOfStrings = map (filter (\c -> isAsciiLower c || isAsciiUpper c))
Related