haskell中的censorword函数

haskell中的censorword函数,haskell,Haskell,我正在研究这个函数,它基本上有两个参数。第一个是 一个数字,第二个是列表。每次我在列表中看到第一个参数时,我都想将其替换为3。我的功能正常。这是: censorword _ [] = [] censorword b (x:xs) | b == x = 3:censorword b xs | otherwise = x:censorword b xs 我的问题是,如何使它适用于字符串。换句话说,我想这样做:审查词“ab”[“cdZ”,ab”]=[“cdZ”

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

censorword _ [] = [] 
censorword b (x:xs) 
        |  b == x = 3:censorword b xs 
        | otherwise = x:censorword b xs
我的问题是,如何使它适用于字符串。换句话说,我想这样做:审查词“ab”[“cdZ”,ab”]=[“cdZ”,“hello”]。在这里,我用hello替换了“ab”


欣赏任何想法。

您只需更改被替换的值(
3
在原始代码中)

此函数可通过
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"]

您只需更改被替换的值(
3
在原始代码中)

此函数可通过
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"]
概括

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
然后

censor
可以简化:

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

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
然后

censor
可以简化:

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

什么不起作用?将3更改为“hello”应该可以。什么不起作用?将3更改为“hello”应该可以。类型批注是可选的。好的,我让它听起来像是解决方案的一部分..修复了。类型批注是可选的。好的,我让它听起来像是解决方案的一部分..修复了。