chtefi
7/24/2016 - 5:11 PM

Memoization in Scala

Memoization in Scala

// another method is to do class Memo[+A, -B](f: A => B) extends (A => B) { ... }
// if concurrency is at stake, consider using a scala.collection.concurrent.TrieMap
def Memo[A, B](f: A => B) = new mutable.HashMap[A, B]() {
  override def apply(key: A): B = {
    getOrElseUpdate(key, f(key))
  }
}

// important to be declared lazy because it's calling itself
// otherwise scala compiler complains with forward reference
lazy val fib: (Int => BigInt) = Memo {
  case 0 => 1
  case 1 => 1
  case n => fib(n-1) + fib(n-2)
}

println(fib(100))