我如何做Haskell中的字符串替换 [英] How do I do String replace in Haskell
问题描述
type M a = [(String,String)]
m = [
(x,a car),
(y,a animal)
]
s =这是x和y
我试图
strRep ms
=>这是一辆汽车和一只动物
<所以这是我迄今为止的尝试
import Data.List.Utils
strRep ::(Show a)=> M - > String - > String
strRep [] s = s
strRep(m:ms)s = replace(fst m)(snd m)s:strRep ms s
上面的代码返回一个字符串列表。
我不知道哪里替换
来自上面的示例。但是......假设它存在,并且做了你所期望的,你应该能够从 strRep $中删除cons
(:)
c $ c>函数,而是将替换结果传递给下一轮strRep,如下所示:
strRep :: (显示a)=> M - >字符串 - >字符串
pre>
strRep [] s = s
strRep(m:ms)s = strRep ms(replace(fst m)(snd m)s)
现在,不是返回一个字符串列表,而是每个版本替换一个东西。您正在迭代替换每个字符串,并将新字符串传递给下一个替换字符串。
So I have the following list of tuples and a string
type M a = [(String, String)] m = [ ("x", "a car"), ("y", "a animal") ] s = "this is x and y"
I am trying to
strRep m s
=> "this is a car and a animal"So this is my attempt so far
import Data.List.Utils strRep :: (Show a) => M -> String -> String strRep [] s = s strRep (m:ms) s = replace (fst m) (snd m) s : strRep ms s
The above code returns a list of string. I cant quite figure out the proper way to do loop here.
解决方案I'm not sure where
replace
is coming from in your example above. But... assuming it exists, and does what you expect, you should be able to remove the cons(:)
from yourstrRep
function, and instead pass the result of replace into the next run of strRep, like so:strRep :: (Show a) => M -> String -> String strRep [] s = s strRep (m:ms) s = strRep ms (replace (fst m) (snd m) s)
Now, instead of returning a list of strings, each a version with one thing replaced. You are iteratively replacing each string, passing the new strings on for the next replacement.
这篇关于我如何做Haskell中的字符串替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!