Joh*_*ohn 4 haskell replace nested list
我必须制作三个函数来替换扁平字符串和列表.
我不知道,是否有像其他语言一样的替换功能.我搜索了但不幸的是没有成功:-(
所以我的尝试还很薄.
第一功能:
replace :: String -> String -> String -> String
replace findStr replaceStr myText = replace()??
Run Code Online (Sandbox Code Playgroud)
我的第一个功能的方法:
replace :: String -> String -> String -> String
replace [] old new = []
replace str old new = loop str
where
loop [] = []
loop str =
let (prefix, rest) = splitAt n str
in
if old == prefix -- found an occurrence?
then new ++ loop rest -- yes: replace
else head str : loop (tail str) -- no: keep looking
n = length old
Run Code Online (Sandbox Code Playgroud)
第二功能:
replaceBasedIdx :: String -> [String] -> String -> String
replaceBasedIdx findStr replaceStrList myText = replace()???
Run Code Online (Sandbox Code Playgroud)
这个函数应该替换myTxt中的第一个findStr和replaceStrList的第一个元素,第二个findStr和第二个元素等等......
例:
replaceBasedIdx "a" ["G","V","X"] "Haskell is a language"
"HGskell is V lXnguage"
Run Code Online (Sandbox Code Playgroud)
我对第二个功能的方法:
replaceBasedIdx :: String -> [String] -> String -> String
replaceBasedIdx findStr replaceStrList myText = replaceBasedIdxSub findStr replaceStrList myText 0
replaceBasedIdxSub :: String -> [String] -> String -> Int -> String
replaceBasedIdxSub findStr replaceStrList myText counter = loop myText
where
loop [] = []
loop myText =
let (prefix, rest) = splitAt n myText
in
if findStr == prefix -- found an occurrence?
then (replaceStrList !! (counter+1)) ++ loop rest -- yes: replace it
else head myText : loop (tail myText) -- no: keep looking
n = length findStr
Run Code Online (Sandbox Code Playgroud)
我现在非常接近最终结果,但计数器不会增加.
你能告诉我,我的错误在哪里吗?我怎么能修改第一个或第二个函数来获得第三个函数呢?
第三功能:
replaceBasedIdxMultiple :: [String] -> [String] -> String -> String
replaceBasedIdxMultiple findStrList replaceStrList myText = replace()???
Run Code Online (Sandbox Code Playgroud)
这个函数应该用来自replaceStrList的相应元素替换myTxt中findStrList的每个元素,所以1.用1.,2.用2.等等......
例:
replaceBasedIdxMultiple ["A","X","G"] ["N","Y","K"] "ABXMG"
"NBYMK"
Run Code Online (Sandbox Code Playgroud)
你能帮帮我吗?一些提示和提示,如何开始呢?
我真是不同:-(
非常感谢提前
亲切的问候!
替换存在于Data.List.Utils,MissingH包的一部分.
实际上,这是一个非常简洁的实现:
replace :: Eq a => [a] -> [a] -> [a] -> [a]
replace old new = join new . split old
Run Code Online (Sandbox Code Playgroud)