0

我正在研究这个基本上需要两个参数的函数。第一个是数字,第二个是列表。每次在列表中看到第一个参数时,我都想用 3 替换它。我的功能工作正常。这里是:

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

我的问题是,我如何使它适用于字符串。换句话说,我想做这样的事情:censorword "ab" ["cdZ",ab"] = ["cdZ","hello"] 在这里,我用你好替换了 "ab"。

欣赏任何想法。

4

2 回答 2

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"]
于 2012-12-15T18:36:03.663 回答
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
于 2012-12-15T18:41:15.707 回答