-
-
Save ilaborie/8e4b8ba4cae7aa20955b to your computer and use it in GitHub Desktop.
Basic Scala Memoïzation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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