[英]Replacing a string in Haskell
我正在嘗試用Haskell中的另一個字符串替換字符串。 這是我到目前為止的代碼,但它並不完全有用。
replace :: [Char] -> [Char]
replace [] = []
replace (h:t) =
if h == "W"
then "VV" : replace t
else h : replace t
我想能夠完成這個例子:如果字符串是“HELLO WORLD”,結果應該是“HELLO VVORLD”。 我認為單詞/單詞會有所幫助,但不完全確定如何實現它。
關於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"
使用模式匹配:
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:)) []
錯誤在"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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.