什么类型用于在Scala中存储内存中的可变数据表?
发布时间:2020-12-16 09:35:09 所属栏目:安全 来源:网络整理
导读:每次调用一个函数时,如果给定的一组参数值的结果尚未记忆,我想将结果放入内存表中。一列旨在存储结果,其他列用于存储参数值。 如何最好地实施?参数有多种类型,包括一些枚举。 在C#中,我通常会使用DataTable。 Scala中有相当的吗? 解决方法 您可以使用
每次调用一个函数时,如果给定的一组参数值的结果尚未记忆,我想将结果放入内存表中。一列旨在存储结果,其他列用于存储参数值。
如何最好地实施?参数有多种类型,包括一些枚举。 在C#中,我通常会使用DataTable。 Scala中有相当的吗? 解决方法
您可以使用mutable.Map [TupleN [A1,A2,…,AN],R],或者如果存储器是WeakHashMap [1]。下面的定义(基于
michid’s blog的记忆代码构建)允许您轻松地使用多个参数记忆功能。例如:
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,T3,T3) => R): ((T1,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.html和this related question。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |