Avah
Avah

Reputation: 227

Mapping the values from a Map to a String in Scala

I have a map like this:

val map: Map[String, Int] = Map("Lit1" -> 8, "Lit2" -> 11, "Lit3" -> 7)

and a formula like this:

val r: String = "(Lit1 & (Lit2 | Lit3) & ~Lit2)"

how I can use the map to map the values for Lit1, Lit2, and Lit3, so that I will have the r string as

val r: String = "(8 & (11 | 7) & ~11)"

Thanks for any help.

Upvotes: 1

Views: 227

Answers (2)

Robby Cornelissen
Robby Cornelissen

Reputation: 97331

You could use a regular expression to find and replace the literals with the values you retrieve from the map:

val map: Map[String, Int] = Map("Lit1" -> 8, "Lit2" -> 11, "Lit3" -> 7)
val r: String = "(Lit1 & (Lit2 | Lit3) & ~Lit2)"
val s: String = """Lit\d+""".r.replaceAllIn(r, m => map(m.group(0)).toString)


println(s) // (8 & (11 | 7) & ~11)

If it's possible that one or more literals are not present in the lookup map, you'd need to use getOrElse:

val map: Map[String, Int] = Map("Lit1" -> 8, "Lit2" -> 11, "Lit3" -> 7)
val r: String = "(Lit1 & (Lit2 | Lit3) & ~Lit2 & Lit4)"
val s: String = """Lit\d+""".r.replaceAllIn(r, m => map.getOrElse(m.group(0), m.group(0)).toString)


println(s) // (8 & (11 | 7) & ~11 & Lit4)

Upvotes: 2

jwvh
jwvh

Reputation: 51271

I think this is what you want.

val map: Map[String, Int] = Map("Lit1" -> 8, "Lit2" -> 11, "Lit3" -> 7)
val r: String = "(Lit1 & (Lit2 | Lit3) & ~Lit2)"

map.foldLeft(r){case (s, (k,v)) => s.replaceAll(k,v.toString)}
// res0: String = (8 & (11 | 7) & ~11)

Fold over the Map key->value pairs, modifying the String on each step.

Upvotes: 4

Related Questions