Created
October 30, 2014 16:40
-
-
Save lanceon/0bc622d891d35dc2188e to your computer and use it in GitHub Desktop.
Memoizes function return value and returns it when called again
This file contains 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
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