Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access and update a value in a mutable map of map of maps

I've a three-level data structure (indentation and line breaks for readability):

scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map

scala> val m = Map("normal" -> Map("home" -> Map("wins" -> 0, "scores" -> 0),
                                   "away" -> Map("wins" -> 0, "scores" -> 0)))
m: scala.collection.mutable.Map[java.lang.String,
   scala.collection.mutable.Map[java.lang.String,
   scala.collection.mutable.Map[java.lang.String,Int]]] = 
Map((normal,Map(away -> Map(wins -> 0, scores -> 0),
     home -> Map(wins -> 0, scores -> 0))))

Accessing the innermost data (scores) requires a lot of typing:

import org.scalatest.{Assertions, FunSuite}

class MapExamplesSO extends FunSuite with Assertions {
  test("Update values in a mutable map of map of maps") {
    import scala.collection.mutable.Map
    // The m map is essentially an accumulator
    val m = Map("normal" -> 
                Map("home" -> Map("wins" -> 0, "scores" -> 0),
                    "away" -> Map("wins" -> 0, "scores" -> 0)
                  )
          )
    //
    // Is there a less verbose way to increment the scores ?
    //
    assert(m("normal").apply("home").apply("scores") === 0)

    val s1 = m("normal").apply("home").apply("scores") + 1
    m("normal").apply("home").update("scores", s1)

    assert(m("normal").apply("home").apply("scores") === 1)

    val s2 = m("normal").apply("home").apply("scores") + 2
    m("normal").apply("home").update("scores", s2)

    assert(m("normal").apply("home").apply("scores") === 3)
  }
}

Is there a less verbose way to modify the value of scores ?

I'm a Scala newbie, so all other observations of the code above are also welcome.

like image 960
user272735 Avatar asked Dec 01 '10 12:12

user272735


1 Answers

You don't have to use "apply" just do it normally with "()"

m("normal")("home")("scores") = 1
like image 91
wheaties Avatar answered Sep 23 '22 21:09

wheaties