I create a simple cache line (to easily cache my functions):
trait Cache[A,B] {
def _calc(v:A):B
private var cache = Map[A,B]()
def calc(v:A):B = {
cache.get(v) match {
case Some(x) => x
case None =>
val x = _calc(v)
cache += (v -> x)
x
}
}
}
Using:
object Sol extends Cache[Int,Int] {
def _calc(v:Int):Int = { }
}
Sol.calc(5)
It works correctly, but the problem arises when I need to cache functions with a large number of arguments - therefore I need to develop features of Cache2, Cache3, all copies of the code in the first value.
A possible workaround is to convert functions with multiple arguments to functions that take a tuple, but that doesn't seem right.
Is there a way to do this more generally and to avoid violating DRY rules ?
source
share