2012-12-15 61 views
0

我正在研究基本上需要兩個參數的函數。第一個是 一個數字,第二個是一個列表。每次我在列表中看到它時,我想用3替換第一個參數。我的功能正常工作。這是它:haskell中的censorword函數

censorword _ [] = [] 
censorword b (x:xs) 
     | b == x = 3:censorword b xs 
     | otherwise = x:censorword b xs 

我的問題是,我如何使它的字符串工作。換句話說,我想做這樣的事情:censorword「ab」[「cdZ」,ab「] = [」cdZ「,」hello「]在這裏,我已經用」hello「代替了」ab「

欣賞任何想法

+1

什麼不起作用?將3改爲「hello」應該沒問題。 –

回答

2

你只需要改變的值被替換(3在原始代碼)

censorword :: String -> [String] -> [String] 
censorword _ [] = [] 
censorword b (x:xs) 
     | b == x = "hello" : censorword b xs 
     | otherwise = x : censorword b xs 

此功能可以概括和簡化了map:。

censorword' :: (Eq a) => a -> a -> [a] -> [a] 
censorword' a b = map (\x -> if x == a then b else x) 

censorword' "ab" "he" ["ab", "he", "ab"] -- => ["he", "he", "he"] 
+0

工作。我不知道我在哪裏混亂。謝謝。 – Stranger

+0

類型註釋是可選的。 – huon

+0

好點,我聽起來像它是解決方案的一部分..修復。 –

1

概括。

censor :: Eq a => a -> a -> [a] -> [a] 
censor _   _  []  = [] 
censor replacement needle (x : xs) 
    | needle == x     = replacement : censor replacement needle xs 
    | otherwise     = x   : censor replacement needle xs 

然後

censorword = censor 3 
censorwordForStrings = censor "hello" 

censor可以簡化爲:

censor :: Eq a => a -> a -> [a] -> [a] 
censor replacement needle = map censor' where 
    censor' x | needle == x = replacement 
       | otherwise = x