, Scala OOP FP Scala .
object CachedFunction extends App {
val f = new Function2[Int, Int, Int] {
def expensiveCalculation(num: Int) = {
println("I've spent a lot of time(!) calculating square of " + num)
num * num
}
var precomputed: Map[Int, Int] = Map()
def getOrUpdate(key: Int): Int =
precomputed.get(key) match {
case Some(v) => v
case None =>
val newV = expensiveCalculation(key)
precomputed += key -> newV
newV
}
def apply(x: Int, y: Int): Int =
getOrUpdate(x) + getOrUpdate(y)
}
def g = f(1, _: Int)
g(2)
g(3)
g(3)
f(1, 2)
}
:
I've spent a lot of time(!) calculating square of 1
I've spent a lot of time(!) calculating square of 2
I've spent a lot of time(!) calculating square of 3
f def val -, f , "" , , . apply, . - OOPish.
, , . , - .
EDIT:
, , googled " memoization" . :
Scala Memoization: Scala ?
memoize Scala?
http://eed3si9n.com/learning-scalaz-day16
-, Scalaz - :)
EDIT:
, Scala , . . :
object CachedArg extends App {
def expensiveCalculation(num: Int) = {
println("I've spent a lot of time(!) calculating square of " + num)
num * num
}
val ff: Int => Int => Int = a => b => expensiveCalculation(a) + expensiveCalculation(b)
val f1 = ff(1)
val e1 = expensiveCalculation(1)
val f: (Int, Int) => Int = _ + expensiveCalculation(_)
val g1 = f(e1, _: Int)
g1(2)
g1(3)
}
I've spent a lot of time(!) calculating square of 1
I've spent a lot of time(!) calculating square of 2
I've spent a lot of time(!) calculating square of 3
, "" , ( ). , . , :
object CachedFunction extends App {
val f = new Function1[Int, Int => Int] {
def expensiveCalculation(num: Int) = {
println("I've spent a lot of time(!) calculating square of " + num)
num * num
}
def apply(x: Int) =
new Function[Int, Int] {
val xe = expensiveCalculation(x)
def apply(y: Int) = xe + expensiveCalculation(y)
}
}
val g1 = f(1) // prints here for eval of 1
g1(2)
g1(3)
}
I've spent a lot of time(!) calculating square of 1
I've spent a lot of time(!) calculating square of 2
I've spent a lot of time(!) calculating square of 3
memoizaition . . , memoizaition , .