Last active
September 6, 2017 11:05
-
-
Save qingwei91/70ca423992940ca7de46e490eb846596 to your computer and use it in GitHub Desktop.
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 CacheBackEnd[K, V] { | |
private var map = Map.empty[K, V] // ignore the fact it is not thread safe | |
// `compute` is a function, only evaluated in case of cache miss | |
def getOrElse(k: K, compute: K => V): V = { | |
map.get(k) match { | |
case Some(v) => v // cache hit | |
case None => | |
val v = compute(k) | |
map = map + (k -> v) | |
v | |
} | |
} | |
} | |
def cache[K, V](fn: K => V)(cacheStorage: CacheBackEnd[K, V]): K => V = { | |
(k: K) => | |
cacheStorage.getOrElse(k, fn) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment