Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala - string modification in a functional manner

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

like image 564
mmmdreg Avatar asked Mar 27 '11 03:03

mmmdreg


1 Answers

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))}
like image 128
sepp2k Avatar answered Sep 28 '22 14:09

sepp2k