繁体   English   中英

如何在String(Haskell)中同时替换多个元素

[英]How to replace more than one element at the same time in a String (Haskell)

我想以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 [] _ _ =[]

但我仍然不知道如何解决这个问题。任何想法?

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

首先,您需要根据find字符串将输入String划分为多个部分( [String] )。 所以这个功能是

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)

另外,您确实需要实现更快的子字符串搜索算法,并考虑用一个Data.Map替换findrepl

我可以看到两个错误:

  1. 始终忽略findrepl的最终元素。 tail find == []tail repl == []时, replaceMore返回text ; 应该在find == []repl == []

    但它们应该被早期的方程式所捕获

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

    哪个,你现在应该能看到,是错的,应该是

     replaceMore _ [] text = text replaceMore [] _ text = text 
  2. 但那时的输出就是

     "The House with House is big" 

    还是错的。 这是因为你正在构建replaceMore out out replace 对于每个搜索词,您搜索文本,找到后将其替换。 所以你用"Mou"代替"Hou" (所以"House""Mouse"代替); 然后你用"House"取代"Mouse" (意思是原来"House"最终再次成为"House" )。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM