What type to use to store an in-memory mutable data table in Scala?

前端 未结 5 1823
不知归路
不知归路 2020-11-28 08:55

Each time a function is called, if it\'s result for a given set of argument values is not yet memoized I\'d like to put the result into an in-memory table. One column is mea

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 09:17

    The version suggested by anovstrup using a mutable Map is basically the same as in C#, and therefore easy to use.

    But if you want you can also use a more functional style as well. It uses immutable maps, which act as a kind of accumalator. Having Tuples (instead of Int in the example) as keys works exactly as in the mutable case.

    def fib(n:Int) = fibM(n, Map(0->1, 1->1))._1
    
    def fibM(n:Int, m:Map[Int,Int]):(Int,Map[Int,Int]) = m.get(n) match {
       case Some(f) => (f, m)
       case None => val (f_1,m1) = fibM(n-1,m)
                    val (f_2,m2) = fibM(n-2,m1)
                    val f = f_1+f_2
                    (f, m2 + (n -> f))   
    }
    

    Of course this is a little bit more complicated, but a useful technique to know (note that the code above aims for clarity, not for speed).

提交回复
热议问题