Haskell用Char替换空间

时间:2014-10-16 13:09:44

标签: haskell

我正在尝试用一个函数替换"%50"或类似的字符串中的所有空格,我知道我弄乱了我的类型的东西,但似乎无法想象它我一直在尝试以下(是的,我已导入Data.Char

newLine :: String -> String
newLine xs = if x `elem` " " then "%50"

我也尝试了if then else语句但是真的不知道该如何处理其他因此只想小写所有字母

newLine xs = [if x `elem` ' ' then '%50' else toLower x | x<-xs]

希望else语句简单地什么也不做,只是搜索过,发现无法做到这一点,所以我想如果一切都是小写的,那么只是试着让它工作起来并不重要。

5 个答案:

答案 0 :(得分:3)

尝试简单的解决方案

newLine :: String -> String
newline ""       = ""
newLine (' ':xs) = '%':'5':'0': newLine xs
newLine (x:xs)   = x: newLine xs

或使用库函数

答案 1 :(得分:0)

您遇到了类型不匹配问题。您正在使用的方法如果您正在用另一个Char替换Char。例如,用星号替换空格:

newLine xs = [if x == ' ' then '*' else toLower x | x<-xs]

或者如果您想用星号替换空格和换行符,可以使用elem函数。但请注意,elem函数采用数组(或字符串,与[Char]相同)。在您的示例中,您尝试将单个元素' '传递给它。这应该有效:

newLine xs = [if x `elem` " \n" then '*' else toLower x | x<-xs]

但是,您希望将Char替换为String[Char])。所以你需要一个不同的方法。 viorior建议的解决方案对我来说很好。

答案 2 :(得分:0)

嗯,列表理解几乎是正确的。问题是:

  • %50”不是有效的字符文字,因此您不能拥有'%50'。如果您实际上是指三个字符 %50,则需要改为String

  • ' ' 正确的字符文字,但字符x不能是另一个字符的元素。你当然只是指x == ' '

现在建议解决方案

    [if x == ' ' then "%50" else toLower x | x<-xs]

但这并不常用,因为你在同一个列表中混合了字符串("%50")和单个字符。通过将x“提升”为单个字符字符串,可以很容易地解决这个问题:

    [if x == ' ' then "%50" else [toLower x] | x<-xs]

然后,结果会输入[String],可以使用前奏concat函数将其“展平”为单个字符串。

     concat [if x == ' ' then "%50" else [toLower x] | x<-xs]

另一种写作方式是

     concatMap (\x -> if x == ' ' then "%50" else [toLower x]) xs

或 - 与more general infix operators

完全相同
     xs >>= \x -> if x == ' ' then "%50" else [toLower x]

答案 3 :(得分:0)

要用可能更长的字符串替换字符,可以采用以下方法:

-- replace single characters
replace :: Char -> String
replace ' ' = "%50"
replace '+' = "Hello" 
replace c | isAlpha c = someStringFunctionOf c
replace _   = "DEFAULT"

-- extend to strings
replaceString :: String -> String
replaceString s = concat (map replace s)

最后一行也可以写成

replaceString s = concatMap replace s

甚至

 replaceString s = s >>= replace

甚至

 replaceString = (>>= replace)

答案 4 :(得分:0)

import Data.List
newLine :: String -> String
newLine  = intercalate "%50" . words