Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do some replacement in Haskell List Comprehensions

My questions is if I put in a string containing such as Hello, today is a Nice Day!! How could I get rid of spaces and punctuation and also replacing the uppercase letters with lowercase?

I know how to delete them but not how to replace them.

Also to get rid of the punctuation.

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

testList xs = [if x = [,|.|?|!] then " "  | x<-xs] 
like image 356
Bob Bobington Avatar asked Mar 10 '13 03:03

Bob Bobington


1 Answers

import Data.Char

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

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

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

If you want to delete the punctuation and convert the 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 don't want or can not import Data.Char, this is an 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
like image 154
Alberto Capitani Avatar answered Sep 23 '22 21:09

Alberto Capitani