gpt4 book ai didi

string - 在 Haskell 中替换字符串

转载 作者:行者123 更新时间:2023-12-01 09:27:07 26 4
gpt4 key购买 nike

我正在尝试用 Haskell 中的另一个字符串替换一个字符串。这是我到目前为止的代码,但它并不完全有效。

replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == "W"
then "VV" : replace t
else h : replace t

我希望能够做到这一点,例如:如果字符串是“HELLO WORLD”,结果应该是“HELLO VVORLD”。我认为 words/unwords 会有所帮助,但不确定如何实现它。

最佳答案

值得明确说明什么 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"

关于string - 在 Haskell 中替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com