[英]Replacing a string in Haskell
I'm trying to replace a string with another string in Haskell. 我正在尝试用Haskell中的另一个字符串替换字符串。 Here's the code that I have so far, but it doesn't exactly work. 这是我到目前为止的代码,但它并不完全有用。
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == "W"
then "VV" : replace t
else h : replace t
I want to be able to accomplish this for example: if the string is "HELLO WORLD", the result should be "HELLO VVORLD". 我想能够完成这个例子:如果字符串是“HELLO WORLD”,结果应该是“HELLO VVORLD”。 I think words/unwords would be helpful, but not exactly sure how to implement it. 我认为单词/单词会有所帮助,但不完全确定如何实现它。
It's worth being explicit about what String
actually is. 关于String
究竟是什么,值得明确。 For instance, you're looking for the test case: 例如,您正在寻找测试用例:
replace ['H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D']
==
['H', 'E', 'L', 'L', 'O', ' ', 'V', 'V', 'O', 'R', 'L', 'D']
Now, when you pattern match on a list like this the head of the list will be the first character of the string 现在,当你在这样的列表上进行模式匹配时,列表的头部将是字符串的第一个字符
> case "Hello world" of (c:rest) -> print c
'H'
So we can't match it with a string literal like "W"
. 所以我们无法将它与像"W"
这样的字符串文字相匹配。 In a similar way, we can't use cons ( (:)
) to prepend a string to another string, we can only add a single character! 以类似的方式,我们不能使用cons( (:)
)将字符串前置到另一个字符串,我们只能添加一个字符!
> 'P' : "hello"
"Phello"
Instead, we'll use (++) :: String -> String -> String
to append two strings. 相反,我们将使用(++) :: String -> String -> String
来追加两个字符串。
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == 'W'
then "VV" ++ replace t
else h : replace t
Which ought to work as expected 哪个应该按预期工作
> replace "Hello World"
"Hello VVorld"
With pattern matching: 使用模式匹配:
replace ('W':xs) = "VV" ++ replace xs
replace (x:xs) = x : replace xs
replace [] = []
With for comprehension: 理解:
replace xs = concat [if x == 'W' then "VV" else [x] | x <- xs]
With monads: 使用monads:
replace = (>>= (\ x -> if x == 'W' then "VV" else [x]))
With a fold: 折叠:
replace = foldr (\ x -> if x == 'W' then ("VV"++) else (x:)) []
The error is in "VV" :: [Char]
but not Char
. 错误在"VV" :: [Char]
但不是Char
。
And "W"
is [Char]
, but not Char
而"W"
是[Char]
,但不是Char
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == 'W'
then 'V' : 'V' : replace t
else h : replace t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.