我的问题是,如果我把一个字符串包含如Hello, today is a Nice Day!!
我怎样才能摆脱空格和标点符号,并用大写字母替换小写?在Haskell List Comprehensions中做一些替换
我知道如何删除它们,但不知道如何替换它们。
同样为了摆脱标点符号。
对不起,我不知道如何处理字符串,只有数字。
testList xs = [if x = [,|.|?|!] then " " | x<-xs]
我的问题是,如果我把一个字符串包含如Hello, today is a Nice Day!!
我怎样才能摆脱空格和标点符号,并用大写字母替换小写?在Haskell List Comprehensions中做一些替换
我知道如何删除它们,但不知道如何替换它们。
同样为了摆脱标点符号。
对不起,我不知道如何处理字符串,只有数字。
testList xs = [if x = [,|.|?|!] then " " | x<-xs]
import Data.Char
如果你想转换的标点符号空间和从大写字符为小写:
testList xs = [if x `elem` ",.?!" then ' ' else toLower x | x<-xs]
例子:testList "TeST,LiST!" == "test list "
如果要删除标点并将字符从大写字母转换为小写字母:
testList2 xs = [toLower x | x<-xs, not (x `elem` ",.?!")]
例子:testList2 "Te..S,!t LiS?T" == "test list"
如果你不想或者不能导入Data.Char,这是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
为了摆脱标点符号的,你可以使用过滤器这样一个
[x | x<-[1..10], x `mod` 2 == 0]
“如果”您正在使用不会过滤。将一个if放置在列表理解的“地图”部分将只能在两个选项中进行选择,但不能将其过滤掉。
至于转换的东西为小写,其同样的招数,你可以在数量上已经决绝:
[x*2 | x <- [1..10]]
我已经不用写在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中,但如果你想自己编写它,请查看Stack Overflow。这个问题之前已经被问到。
这里有一个版本,但不导入模块,使用fromEnum和toEnum来选择允许的字符:
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"
对于模块少替换功能,这样的事情可能工作:
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"
请记住,OP也想用一个空格替换一些字符。 – 2013-03-10 04:41:44
您将在Data.Char
找到所需的功能:
import Data.Char
process str = [toLower c | c <- str , isAlpha c]
虽然就个人而言,我觉得功能成分的做法是清晰的:
process = map toLower . filter isAlpha
这不能解决问题--OP想要用空格替换无效字符,而不是删除它们。请参阅@ OscarMederos的回答。 – luqui 2013-03-10 08:23:28
“我怎样才能摆脱空格和标点符号,并用小写字母替换大写字母?”这听起来像OP想要删除空格。 – 2013-03-10 08:51:57
也许如果他的意思是别的,OP可以编辑这个问题来澄清问题。 – 2013-03-10 08:53:57
这应该是我的回答中的一条评论。你有没有看过它? – 2013-03-10 08:31:30
这非常有帮助。谢谢。教授给我们的力量只有数字的例子,但这清除了我操纵字母的很多问题。 – 2013-03-10 22:02:33
但是我将如何实现toLower?它给我不在范围内,我试着添加import data.char,但是这也给我一个错误。编辑:我知道它工作nvm。 – 2013-03-10 22:08:39