Skip to content

Instantly share code, notes, and snippets.

@ilaborie
Last active August 29, 2015 14:04
Show Gist options
  • Save ilaborie/8e4b8ba4cae7aa20955b to your computer and use it in GitHub Desktop.
Save ilaborie/8e4b8ba4cae7aa20955b to your computer and use it in GitHub Desktop.
Basic Scala Memoïzation
case class Memo[A, B](f: A => B) extends Function1[A, B] {
private val cache = scala.collection.mutable.Map.empty[A, B]
def apply(x: A) = cache.getOrElseUpdate(x, f(x))
}
val fibonacci: Memo[Int, Int] = Memo {
case 0 => 0
case 1 => 1
case n => fibonacci(n - 1) + fibonacci(n - 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment