在Scala中用于存储内存中可变数据表的类型是什么?

时间:2010-09-04 03:50:29

标签: scala data-structures memoization scala-collections

每次调用一个函数时,如果给定的一组参数值的结果尚未被记忆,我想将结果放入内存表中。一列用于存储结果,另一列用于存储参数值。

我如何才能最好地实现这一目标?争论的种类繁多,包括一些枚举。

在C#中,我通常使用DataTable。 Scala中有等效的吗?

5 个答案:

答案 0 :(得分:25)

您可以使用mutable.Map[TupleN[A1, A2, ..., AN], R] ,或者如果关注内存,则使用WeakHashMap [1]。下面的定义(基于michid's blog的memoization代码构建)允许您轻松地记忆具有多个参数的函数。例如:

import Memoize._

def reallySlowFn(i: Int, s: String): Int = {
   Thread.sleep(3000)
   i + s.length
}

val memoizedSlowFn = memoize(reallySlowFn _)
memoizedSlowFn(1, "abc") // returns 4 after about 3 seconds
memoizedSlowFn(1, "abc") // returns 4 almost instantly

说明:

/**
 * A memoized unary function.
 *
 * @param f A unary function to memoize
 * @param [T] the argument type
 * @param [R] the return type
 */
class Memoize1[-T, +R](f: T => R) extends (T => R) {
   import scala.collection.mutable
   // map that stores (argument, result) pairs
   private[this] val vals = mutable.Map.empty[T, R]

   // Given an argument x, 
   //   If vals contains x return vals(x).
   //   Otherwise, update vals so that vals(x) == f(x) and return f(x).
   def apply(x: T): R = vals getOrElseUpdate (x, f(x))
}

object Memoize {
   /**
    * Memoize a unary (single-argument) function.
    *
    * @param f the unary function to memoize
    */
   def memoize[T, R](f: T => R): (T => R) = new Memoize1(f)

   /**
    * Memoize a binary (two-argument) function.
    * 
    * @param f the binary function to memoize
    * 
    * This works by turning a function that takes two arguments of type
    * T1 and T2 into a function that takes a single argument of type 
    * (T1, T2), memoizing that "tupled" function, then "untupling" the
    * memoized function.
    */
   def memoize[T1, T2, R](f: (T1, T2) => R): ((T1, T2) => R) = 
      Function.untupled(memoize(f.tupled))

   /**
    * Memoize a ternary (three-argument) function.
    *
    * @param f the ternary function to memoize
    */
   def memoize[T1, T2, T3, R](f: (T1, T2, T3) => R): ((T1, T2, T3) => R) =
      Function.untupled(memoize(f.tupled))

   // ... more memoize methods for higher-arity functions ...

   /**
    * Fixed-point combinator (for memoizing recursive functions).
    */
   def Y[T, R](f: (T => R) => T => R): (T => R) = {
      lazy val yf: (T => R) = memoize(f(yf)(_))
      yf
   }
}

定点组合子(Memoize.Y)可以记忆递归函数:

val fib: BigInt => BigInt = {                         
   def fibRec(f: BigInt => BigInt)(n: BigInt): BigInt = {
      if (n == 0) 1 
      else if (n == 1) 1 
      else (f(n-1) + f(n-2))                           
   }                                                     
   Memoize.Y(fibRec)
}

[1] WeakHashMap不能很好地用作缓存。请参阅http://www.codeinstructions.com/2008/09/weakhashmap-is-not-cache-understanding.htmlthis related question

答案 1 :(得分:10)

anovstrup使用可变Map建议的版本与C#中的版本基本相同,因此易于使用。

但如果你想要,你也可以使用更实用的风格。它使用不可变映射,它充当一种控制器。使用元组(而不是示例中的Int)作为键的工作方式与可变的情况完全相同。

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))   
}

当然这有点复杂,但却是一种有用的技术(注意上面的代码是为了清晰,而不是速度)。

答案 2 :(得分:3)

作为这个主题的新手,我完全不了解所给出的任何例子(但无论如何都要感谢)。恭敬地,我会为这个案例提出我自己的解决方案,有些人来到这里有同样的水平和相同的问题。对于任何只有the very-very basic Scala knowledge的人来说,我认为我的代码可以清晰明了。



def MyFunction(dt : DateTime, param : Int) : Double
{
  val argsTuple = (dt, param)
  if(Memo.contains(argsTuple)) Memo(argsTuple) else Memoize(dt, param, MyRawFunction(dt, param))
}

def MyRawFunction(dt : DateTime, param : Int) : Double
{
  1.0 // A heavy calculation/querying here
}

def Memoize(dt : DateTime, param : Int, result : Double) : Double
{
  Memo += (dt, param) -> result
  result
}

val Memo = new  scala.collection.mutable.HashMap[(DateTime, Int), Double]


完美无缺。我很欣赏批评如果我错过了什么。

答案 3 :(得分:1)

当使用可变地图进行记忆时,应记住这会导致典型的并发问题,例如:当写还没有完成时做一个get。但是,线程安全的memoization尝试建议这样做,即使不是没有价值也没什么价值。

以下线程安全代码创建一个memoized fibonacci函数,启动几个调用它的线程(从'a'到'd'命名)。尝试几次代码(在REPL中),可以很容易地看到f(2) set被多次打印。这意味着线程A已经启动了f(2)的计算,但线程B完全不了解它并开始自己的计算副本。这种无知在缓存的构建阶段是如此普遍,因为所有线程都没有看到已建立的子解决方案,并且会输入else子句。

object ScalaMemoizationMultithread {

  // do not use case class as there is a mutable member here
  class Memo[-T, +R](f: T => R) extends (T => R) {
    // don't even know what would happen if immutable.Map used in a multithreading context
    private[this] val cache = new java.util.concurrent.ConcurrentHashMap[T, R]
    def apply(x: T): R =
      // no synchronized needed as there is no removal during memoization
      if (cache containsKey x) {
        Console.println(Thread.currentThread().getName() + ": f(" + x + ") get")
        cache.get(x)
      } else {
        val res = f(x)
        Console.println(Thread.currentThread().getName() + ": f(" + x + ") set")
        cache.putIfAbsent(x, res) // atomic
        res
      }
  }

  object Memo {
    def apply[T, R](f: T => R): T => R = new Memo(f)

    def Y[T, R](F: (T => R) => T => R): T => R = {
      lazy val yf: T => R = Memo(F(yf)(_))
      yf
    }
  }

  val fibonacci: Int => BigInt = {
    def fiboF(f: Int => BigInt)(n: Int): BigInt = {
      if (n <= 0) 1
      else if (n == 1) 1
      else f(n - 1) + f(n - 2)
    }

    Memo.Y(fiboF)
  }

  def main(args: Array[String]) = {
    ('a' to 'd').foreach(ch =>
      new Thread(new Runnable() {
        def run() {
          import scala.util.Random
          val rand = new Random
          (1 to 2).foreach(_ => {
            Thread.currentThread().setName("Thread " + ch)
            fibonacci(5)
          })
        }
      }).start)
  }
}

答案 4 :(得分:0)

除了Landei的答案之外,我还想建议在Scala中使用自下而上(非记忆化)方式进行DP,并且核心思想是使用foldLeft(s )。

计算斐波那契数的例子

  def fibo(n: Int) = (1 to n).foldLeft((0, 1)) {
    (acc, i) => (acc._2, acc._1 + acc._2)
  }._1

增长最长的子序列的示例

def longestIncrSubseq[T](xs: List[T])(implicit ord: Ordering[T]) = {
  xs.foldLeft(List[(Int, List[T])]()) {
    (memo, x) =>
      if (memo.isEmpty) List((1, List(x)))
      else {
        val resultIfEndsAtCurr = (memo, xs).zipped map {
          (tp, y) =>
            val len = tp._1
            val seq = tp._2
            if (ord.lteq(y, x)) { // current is greater than the previous end
              (len + 1, x :: seq) // reversely recorded to avoid O(n)
            } else {
              (1, List(x)) // start over
            }
        }
        memo :+ resultIfEndsAtCurr.maxBy(_._1)
      }
  }.maxBy(_._1)._2.reverse
}