0

This is what I tried:

def doStringReplcements(originalStr: String, replacementsMap: Map[String,String]): String = {
  var newStr = originalStr
  replacementsMap.foreach { pair => 
     newStr = newStr.replaceAllLiterally(pair._1, pair._2)
  }
  newStr
}

But functional programming style recommends avoiding vars so how do I do this with just vals?

2
  • Your code doesn't work, functional or not? replaceAllLiterally returns the new string, it doesn't change newStr. newStr = newStr.replaceAllLiterally is needed... Commented Sep 30, 2015 at 11:38
  • @TheArchetypalPaul was a typo, fixed, thx Commented Sep 30, 2015 at 13:14

2 Answers 2

4

Consider using the foldLeft function on Map.

e.g.

replacementsMap.foldLeft(originalStr){ case (accumulator, (target, replacement)) => 
    accumulator.replaceAllLiterally(target, replacement)      
} 
Sign up to request clarification or add additional context in comments.

1 Comment

This has two disadvantages, making multiple passes over the text, and also performing replacements on previous replacements: "ab" -> "Ab" then "Ab" is eligible for match, even though not in the original text.
2

Consider a regex:

scala> import util.matching.Regex
import util.matching.Regex

scala> val text = "one in hand, two in bush"
text: String = one in hand, two in bush

scala> val reps = Map("one"->"lots","two"->"more")
reps: scala.collection.immutable.Map[String,String] = Map(one -> lots, two -> more)

scala> val r = reps.keys.mkString("|").r
r: scala.util.matching.Regex = one|two

scala> r.replaceAllIn(text, m=>reps(m.matched))
res0: String = lots in hand, more in bush

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.