2014-10-16 47 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