Skip to content

Instantly share code, notes, and snippets.

@tifletcher
Created January 19, 2017 17:42
Show Gist options
  • Save tifletcher/1911e97cfd8fdda07afe4cbe6e4fdd38 to your computer and use it in GitHub Desktop.
Save tifletcher/1911e97cfd8fdda07afe4cbe6e4fdd38 to your computer and use it in GitHub Desktop.
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