Reputation: 31
I have a question. I have this line of code here.
map length [filter (/= ' ') someString]
I know it removes the space from someString. But is it possible to remove more than just the space from the string using filter? Let just say remove the spaces and some other char.
Thanks!
Upvotes: 0
Views: 1360
Reputation: 42597
A slightly shorter way is to use notElem
:
λ> filter (flip notElem " f") "foo bar"
"oobar"
Upvotes: 4
Reputation: 21757
An alternative is to use a fold to get the length, if you don't actually need to return the filtered string but only want its length.
f x charlist = foldl (\acc x -> if not $ x `elem` charlist then acc + 1 else acc) 0 x
charlist
is your list of banned characters. If you have a fixed list always, you can directly define it as a top-level value and use it in the function body instead of passing it as a parameter.
A more concise version using list comprehensions:
f x = length [z | z <- x, notElem z charlist]
Upvotes: 1
Reputation: 7350
You can just do:
filter (not . flip elem "<your chars here>")
Example:
ghci> filter (not . flip elem " .,") "This is an example sentence, which uses punctuation."
"Thisisanexamplesentencewhichusespunctuation"
Just to put the comment in here: To filter out letters of both cases (a-z and A-Z), you should probably use Data.Char
's isLetter
function.
Upvotes: 5