Skip to content

Instantly share code, notes, and snippets.

@lanceon
Created October 30, 2014 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lanceon/0bc622d891d35dc2188e to your computer and use it in GitHub Desktop.
Save lanceon/0bc622d891d35dc2188e to your computer and use it in GitHub Desktop.
Memoizes function return value and returns it when called again
class Memoize1[-T, +R](f: T => R) extends (T => R) {
import scala.collection.mutable
private[this] val vals = mutable.Map.empty[T, R]
def apply(x: T): R = {
if (vals.contains(x)) {
vals(x)
}
else {
val y = f(x)
vals += ((x, y))
y
}
}
}
object Memoize1 {
def apply[T, R](f: T => R) = new Memoize1(f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment