0

我想拿2个这样的清单;

find=["Hou","House","Mouse"]
repl=["Mou","Bird","House"]

所以当我给出这样的文字时;

"The House with Mouse is big"

输出应该是这样的;

"The Mouse with House is big"

所以我写了这个;

replace :: String->String->String->String
replace _ _ []=[]

replace find repl text
  = if take(length find) text == find
      then repl ++ replace find repl (drop (length find) text)
      else [head text] ++ (replace find repl (tail text))

replaceMore ::[String]->[String]->String->String
replaceMore _ _ []=[]
replaceMore _ [] _ =[]
replaceMore [] _ _ =[]
replaceMore find repl text
  = if (tail find) == [] || (tail repl)==[]
      then text
      else replaceMore (tail find)
                       (tail repl)
                       (replace (head find) (head repl) text)

它返回

"The Mouse with Mouse is big"

所以它不像我想要的那样工作,我认为问题就在这里;

replaceMore _ _ []=[]
replaceMore _ [] _ =[]
replaceMore [] _ _ =[]

但我仍然不知道如何解决这个问题。所以有什么想法吗?

4

2 回答 2

2

我可能会给你一些关于工作算法的想法。

首先,您需要根据您的字符串将输入String分成几部分 ( )。所以这个函数是[String]find

divideIntoParts :: [String] -> String -> [String]

它的工作原理类似于

divideIntoParts find "The House with Mouse is big"

["The ", "Hou", "se with ", "Mouse", " is big"]

因此,它从字符串中提取要替换的部分,但通过将其他部分保留在同一列表中来保留字母顺序。天真的实现可能看起来像这样

https://gist.github.com/Shekeen/5523749

接下来,您将需要一个函数来扫描此列表并更换需要更换的部件。签名将是

replaceParts :: [String] -> [String] -> [String] -> String

replaceParts find repl $ divideIntoParts find "The House with Mouse is big"

将会

"The Mouse with House is big"

所以你的完整replace功能看起来像

replacePatterns :: [String] -> [String] -> String -> String
replacePatterns find repl = (replaceParts find repl) . (divideIntoParts find)

此外,您确实需要实现更快的子字符串搜索算法并考虑将findand替换replData.Map

于 2013-05-05T10:38:08.263 回答
0

我可以看到两个错误:

  1. find和的最后一个元素repl总是被忽略。replaceMore回馈textwhentail find == []tail repl == []; 那应该是 whenfind == []repl == []

    但它们应该被早期的方程捕捉到

    replaceMore _ [] _ =[]
    replaceMore [] _ _ =[]
    

    哪个,你现在应该可以看到,是错误的,应该是

    replaceMore _ [] text = text
    replaceMore [] _ text = text
    
  2. 但随后的输出将是

    "The House with House is big"
    

    还是错了。这是因为你正在replaceMore向外扩展replace。对于每个搜索词,您搜索文本,找到时替换它。所以你替换"Hou""Mou"(所以"House"替换为"Mouse");然后你替换"Mouse""House"(意思是原来"House"的结果"House"又是)。

    相反,您应该搜索一次文本,在浏览文本之前查找某个位置的每个搜索词。

于 2013-05-05T10:40:26.760 回答