我正在尝试用Haskell中的另一个字符串替换字符串。这是我到目前为止的代码,但它并不完全有用。
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == "W"
then "VV" : replace t
else h : replace t
我希望能够做到这一点:例如:如果字符串是“HELLO WORLD”,结果应为“HELLO VVORLD”。我认为单词/单词会有所帮助,但不完全确定如何实现它。
答案 0 :(得分:5)
值得明确String
实际上是什么。例如,您正在寻找测试用例:
replace ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
==
['H', 'E', 'L', 'L', 'O', ' ', 'V', 'V', 'O', 'R', 'L', 'D']
现在,当你在这样的列表上进行模式匹配时,列表的头部将是字符串的第一个字符
> case "Hello world" of (c:rest) -> print c
'H'
因此我们无法将其与"W"
之类的字符串文字相匹配。以类似的方式,我们不能使用cons((:)
)将字符串前置到另一个字符串,我们只能添加一个字符!
> 'P' : "hello"
"Phello"
相反,我们将使用(++) :: String -> String -> String
附加两个字符串。
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == 'W'
then "VV" ++ replace t
else h : replace t
哪个应该按预期工作
> replace "Hello World"
"Hello VVorld"
答案 1 :(得分:3)
使用模式匹配:
replace ('W':xs) = "VV" ++ replace xs
replace (x:xs) = x : replace xs
replace [] = []
理解:
replace xs = concat [if x == 'W' then "VV" else [x] | x <- xs]
使用monads:
replace = (>>= (\ x -> if x == 'W' then "VV" else [x]))
带折:
replace = foldr (\ x -> if x == 'W' then ("VV"++) else (x:)) []
答案 2 :(得分:0)
错误位于"VV" :: [Char]
但不是Char
。
而"W"
是[Char]
,而不是Char
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == 'W'
then 'V' : 'V' : replace t
else h : replace t