[英]Need help - Haskell Replace
我需要將一個字符串列表中的一個字符串(如果一個字符串只是一個字母,則更改為字符)更改為另一個列表中的另一個字符串。 簽名如下所示:
replace :: [(String, String)] -> String -> String
我應該使用words
/ unwords
功能。 例如,我有[("train","Car")]
“ John被火車撞了。” 如果我運行它,結果必須是“約翰被車撞了”。 您會看到“火車”字符串被替換為“汽車”之一。
我嘗試了一切,但無法解決。 你能幫我嗎?
讓我們使用map change
將change
函數應用於每個字符串。
lookup :: Eq a => a -> [(a, b)] -> Maybe b
檢查匹配的a
對的列表,如果找到Just b
則給Just b
,否則返回Nothing
。 讓我們來看看輸出lookup oldString changeList
並更換Nothing
用S oldString
如果我們得到它,但使用newString
如果我們得到一個:
replace changeList input = map change input where
change oldString = case lookup oldString changeList of
Just newString -> newString
Nothing -> oldString
我不確定我是否理解您的問題,但您可能想要
replace xs w w' = map (\(a,b) -> (a,if b == w then w' else b)) xs
例如: replace [(1,2), (3,2), (5,4)] 2 0
=> [(1,0), (3,0), (5,4)]
。 此函數可以概括,並且應該在字符串上工作。
請注意,其他提供的解決方案更慣用。 由於聽起來像您正在被教,並且需要以這種方式構造它,所以下面是一個使用words
/ unwords
和顯式遞歸的示例:
replace :: [(String, String)] -> String -> String
replace a b = unwords $ foldl inner (words b) a
where inner ls tup = replace' tup ls
replace' :: (String, String) -> [String] -> [String]
replace' tup (x:xs)
| x == fst tup = snd tup : replace' tup xs
| otherwise = x : replace' tup xs
replace' _ [] = []
使用標點符號時,這種words
方法會中斷,但適用於簡單的示例:
*Main> replace [("train", "car"), ("dog", "cat")] "dog cannot drive a train"
"cat cannot drive a car"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.