2014-10-16 45 views
0

我想要拿出一个函数,将用"%50"或类似的字符串替换字符串中的所有空格,我知道我搞乱了一些与我的类型,但似乎无法弄明白我一直在尝试以下(是的,我已经导入Data.CharHaskell用字符替换空间

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

我也试了,如果再else语句,但真的不知道该怎么与别的客人那样想通只是小写所有字母做与

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

想要别人的s因为我没有办法做到这一点,所以我想如果一切都小写,只是试图让这个工作起来并不重要。

回答

2

尝试简单的解决方案

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

或使用

+0

这看起来简单很多,我总是思前想这些事情该帮助非常感谢,虽然我得到以下错误,所以它的一半是:“test%50spaces ***例外:WebAdd.hs:(21,1) - (22,32):否函数newLine中的n-exhaustive模式有关如何解决此问题的任何想法? – Abstract3000 2014-10-16 13:28:29

+1

这是因为缺少空字符串的情况下,您需要添加以下行:'newline [] = []'(或等同于:'newline“”=“”') – Tarmil 2014-10-16 13:45:04

+0

@Tarmil谢谢,我快速回复 – viorior 2014-10-16 13:53:41

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] 

但是,你要替换为String[Char])一Char。所以你需要一个不同的方法。 viorior建议的解决方案对我来说看起来不错。

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] 
+0

这不会*这也*将字符串转换为小写? – 2014-10-16 13:24:58

+0

当然可以。我明白OP也想要这个,尽管我不确定。 – leftaroundabout 2014-10-16 13:25:53

+0

噢,是的,它在问题的代码中,我的错。 – 2014-10-16 13:26:42

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) 
0
import Data.List 
newLine :: String -> String 
newLine = intercalate "%50" . words