我如何做Haskell中的字符串替换 [英] How do I do String replace in Haskell

查看:107
本文介绍了我如何做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 (:) c $ c>函数,而是将替换结果传递给下一轮strRep,如下所示:

  strRep :: (显示a)=> M  - >字符串 - >字符串
strRep [] s = s
strRep(m:ms)s = strRep ms(replace(fst m)(snd m)s)
pre>

现在,不是返回一个字符串列表,而是每个版本替换一个东西。您正在迭代替换每个字符串,并将新字符串传递给下一个替换字符串。


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 your strRep 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆