Created
January 19, 2017 17:42
-
-
Save tifletcher/1911e97cfd8fdda07afe4cbe6e4fdd38 to your computer and use it in GitHub Desktop.
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
import scala.collection.mutable | |
// largely cribbed from http://stackoverflow.com/q/16257378 | |
object Memoize { | |
/** | |
* Simple memoizer backed by a mutable hashmap. Probably not thread safe. | |
* @param f function to be memoized | |
* @tparam K function parameter type | |
* @tparam V function return type | |
* @return memoized f | |
*/ | |
def simple[K, V](f: K => V) = new mutable.HashMap[K, V]() { cache => | |
override def apply(key: K): V = cache.getOrElseUpdate(key, f(key)) | |
} | |
/** | |
* mutable.Hashmap-backed memoizer with synchronized access | |
* @param f function to be memoized | |
* @tparam K function parameter type | |
* @tparam V function return type | |
* @return memoized f | |
*/ | |
def synchronized[K, V](f: K => V) = new mutable.HashMap[K, V]() { cache => | |
override def apply(key: K): V = cache.synchronized { | |
cache.getOrElseUpdate(key, f(key)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment