2017-05-05 77 views
0

我想寫一個函數,它接受一個字符串並用7替換字符串中的任意數字。例如,「foo123」將替換爲「foo777」Haskell中這個替換函數的錯誤在哪裏?

這是我的功能。

replace [] = [] 
replace (x:xs) = 
    if x == ['0'..'9'] 
    then '7' : replace xs 
    else x : replace xs 
+0

你有什麼用呢? –

+1

這甚至不應該編譯,你試圖將x與列表進行比較,所以Haskell會假設你想匹配列表。 [可能的副本](http://stackoverflow.com/questions/14880299/how-can-i-replace-a-substring-of-a-string-with-another-in-haskell-without-using) – mfeineis

回答

2

==只測試x是否等於列表,它不是。您必須使用函數elem,該函數將其中的一個元素和一個元素列表作爲參數,如果該元素在列表中,則返回true。所以,你的代碼將是:

replace [] = [] 
replace (x:xs) = 
    if elem x ['0'..'9'] 
    then '7' : replace xs 
    else x : replace xs 
6

==不測試,如果x是列表中的一個元素;它檢查x是否爲等於到列表中。改用elem函數。

replace [] = [] 
replace (x:xs) = 
    if x `elem` ['0'..'9'] 
    then '7' : replace xs 
    else x : replace xs 

if是一個純粹的表達式,可以在任何地方使用,可以使用另一種表達方式,所以你不需要遞歸調用重複到xs

replace [] = [] 
replace (x:xs) = (if x `elem` ['0'..'9'] then '7' else x) : replace xs 

最後,你可以只使用map而不是使用顯式遞歸。

replace xs = map (\x -> if x `elem` ['0'..'9'] then '7' else x) xs 

或只是

replace = map (\x -> if x `elem` ['0'..'9'] then '7' else x) 

您可能需要使用Data.Char.isDigit代替:

import Data.Char 
replace = map (\x -> if isDigit x then '7' else x)