Make some replacements in the Haskell List Comprehensions

My questions are: if I put a line containing such as Hello, today is a Nice Day!!How can I get rid of spaces and punctuation marks, and also replace uppercase letters with lowercase letters?

I know how to remove them, but not how to replace them.

Also to get rid of punctuation.

Sorry, I don’t know how to mess with strings, only numbers.

testList xs = [if x = [,|.|?|!] then " "  | x<-xs] 
+5
source share
5 answers
import Data.Char

If you want to convert punctuation to space and characters from uppercase to lowercase:

testList xs = [if x `elem` ",.?!" then ' ' else toLower x | x<-xs]

Example: testList "TeST,LiST!" == "test list "

If you want to remove punctuation and convert characters from upper case to lower case:

testList2 xs = [toLower x | x<-xs, not (x `elem` ",.?!")]

Example: testList2 "Te..S,!t LiS?T" == "test list"

If you do not want or cannot import Data.Char, this is the implementation of toLower:

toLower' :: Char -> Char
toLower' char 
    | isNotUppercase = char -- no change required
    | otherwise = toEnum (codeChar + diffLowerUpperChar) -- char lowered
    where
      codeChar = fromEnum char -- each character has a numeric code
      code_A = 65
      code_Z = 90
      code_a = 97
      isNotUppercase = codeChar < code_A || codeChar > code_Z
      diffLowerUpperChar = code_a - code_A
+7

Haskell, ( ), :

import Data.Char

replace invalid xs = [if elem x invalid then ' ' else toLower x | x <- xs]

:

repl invalid [] = []
repl invalid (x:xs) | elem x invalid = ' ' : repl invalid xs
                    | otherwise      = toLower x : repl invalid xs

replace ( repl) :

replace ",.?!" "Hello, today is a Nice Day!!"

:

"hello  today is a nice day  "

: toLower Data.Char Haskell, , , . .

+4

, Data.Char:

import Data.Char

process str = [toLower c | c <- str , isAlpha c]

, :

process = map toLower . filter isAlpha
+4

, ,

[x | x<-[1..10], x `mod` 2 == 0]

"" , . if, "" , .

As for converting things to lowercase, the same trick you can already do in numbers:

[x*2 | x <- [1..10]]
+2
source

Here's the version without importing modules, using fromEnum and toEnum to choose which characters to allow:

testList xs = 
  filter (\x -> elem (fromEnum x) ([97..122] ++ [32] ++ [48..57])) $ map toLower' xs 
    where toLower' x = if elem (fromEnum x) [65..90] 
                          then toEnum (fromEnum x + 32)::Char 
                          else x

OUTPUT:
*Main> testList "Hello, today is a Nice Day!!"
"hello today is a nice day"

For a replacement function without a module, something like this might work:

myReplace toReplace xs = map myReplace' xs where
  myReplace' x
    | elem (fromEnum x) [65..90] = toEnum (fromEnum x + 32)::Char
    | elem x toReplace           = ' '
    | otherwise                  = x

OUTPUT:
*Main> myReplace "!," "Hello, today is a Nice Day!! 123"
"hello  today is a nice day   123"
0
source

All Articles