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))}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With