Scala - 以功能方式修改字符串 [英] Scala - string modification in a functional manner

查看:132
本文介绍了Scala - 以功能方式修改字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



只是想知道是否有更实用的方法来实现某些功能如下所示:

  def expand(exp:String):String = {
var result = exp $ b $ (b)为((k,v)< - libMap){result = result.replace(k,(%s).format(v))}
结果
}

或者一般而言,给定一个字符串和一些可迭代集合,遍历集合并为每个元素增量修改输入字符串。



干杯

解决方案



  var result = init 
for(foo< - bar){result = f(result,foo)}
结果

可以在功能上表示为

  bar.foldLeft(init)(f)

case this becomas:

  l ibMap.foldLeft(exp){case(result,(k,v))=> result.replace(k,(%s)。format(v))} 


I'm just starting Scala and so getting my head around doing things in a more functional style.

Just wondering if there is a more functional way to achieve something like the following:

def expand(exp: String): String = {
  var result = exp
  for ((k,v) <- libMap) {result = result.replace(k, "(%s)".format(v))}
  result
}

Or in general terms, given a string and some iterable collection, go through the collection and for every element, incrementally modify the input string.

Cheers

解决方案

Generally the pattern

var result = init
for (foo <- bar) { result = f(result, foo)}
result

can be expressed functionally as

bar.foldLeft(init)(f)

So for your case this becomas:

libMap.foldLeft(exp){ case(result, (k,v)) => result.replace(k, "(%s)".format(v))}

这篇关于Scala - 以功能方式修改字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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