需要帮助 - Haskell替换

时间:2014-02-27 16:41:28

标签: string list haskell replace

我需要从字符串列表中更改一个字符串(如果字符串只是一个字母,则为chars),而另一个列表中的另一个字符串。签名如下所示:

replace :: [(String, String)] -> String -> String

我应该使用函数words / unwords。例如我有[("train","Car")]“约翰被火车撞了。”如果我跑它,结果必须是“约翰被车撞了。”。你看到“火车”字符串被替换为“汽车”字符串。

我尝试了一切,但我无法理解。 你能帮我解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

让我们使用map changechange函数应用于每个字符串。

lookup :: Eq a => a -> [(a, b)] -> Maybe b会检查匹配a的对列表,如果找到,则为Just b,否则为Nothing。让我们检查一下lookup oldString changeList的输出,如果我们得到Nothing,请用oldString替换newString,如果我们得到replace changeList input = map change input where change oldString = case lookup oldString changeList of Just newString -> newString Nothing -> oldString ,请使用{{1}}:

{{1}}

答案 1 :(得分:0)

我不确定我理解你的问题,但你可能想要

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)]。这个函数概括,并且应该对字符串起作用。

答案 2 :(得分:0)

请注意,其他提供的解决方案更为惯用。既然听起来像是在教你并且需要以这种方式构建它,这里有一个使用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"
相关问题