object Main { def square(v: Int): Int = v * v def cube(v: Int): Int = v * v * v def abs(v: Int): Int = if (v < 0) -v else v def fun(v: Int): Int = { 4 * cube(v) + 2 * square(v) + abs(v) } println(fun(42)) }
object Main { def square(v: Int): Int = v * v def cube(v: Int): Int = v * v * v def abs(v: Int): Int = if (v < 0) -v else v // // ( ), def fun( square: Int => Int, cube: Int => Int, abs: Int => Int) (v: Int): Int = { 4 * cube(v) + 2 * square(v) + abs(v) } // - , // def memoize[A, B](f: A => B): A => B = new mutable.HashMap[A, B] { override def apply(key: A): B = getOrElseUpdate(key, f(key)) } val cachedCube = memoize(cube) // cachedFun - , cube. - val cachedFun: Int => Int = fun( square = square, cube = cachedCube, abs = abs) println(cachedFun(42)) }
object Test3 { trait Ops { def square(v: Int): Int = v * v def cube(v: Int): Int = v * v * v def abs(v: Int): Int = if (v < 0) -v else v } def fun( // , ? ops: Ops) (v: Int): Int = { 4 * ops.cube(v) + 2 * ops.square(v) + ops.abs(v) } // - // - // .. - , Map , // - . Guava . val cachedOps = new Ops { val cache = mutable.HashMap.empty[Int, Int] override def cube(v: Int): Int = cache.getOrElseUpdate(v, super.cube(v)) } val realFun: Int => Int = fun(cachedOps) println(realFun(42)) }
object Main { trait Ops { def square(v: Int): Int = v * v def cube(v: Int): Int = v * v * v def abs(v: Int): Int = if (v < 0) -v else v } class MyFunctions(ops: Ops) { def fun(v: Int): Int = { 4 * ops.cube(v) + 2 * ops.square(v) + ops.abs(v) } } val cachedOps = new Ops { val cache = mutable.HashMap.empty[Int, Int] override def cube(v: Int): Int = cache.getOrElseUpdate(v, super.cube(v)) } val myFunctions = new MyFunctions(cachedOps) println(myFunctions.fun(42)) }
Source: https://habr.com/ru/post/331130/
All Articles