Skip to content

Instantly share code, notes, and snippets.

@wheaties
Created July 24, 2013 19:10
Show Gist options
  • Save wheaties/6073522 to your computer and use it in GitHub Desktop.
Save wheaties/6073522 to your computer and use it in GitHub Desktop.
Cache.scala (this time public)
asdf//In reality, this is all we need, no?
//See https://github.com/jsr107/jsr107spec
trait Cache[Key,Value]{
def get(key: Key): Option[Key]
def getOrElse(key: Key, value: Value) = get(key) getOrElse value
def set(key: Key, value: Value): Value
def contains(key: Key): Boolean
def replace(key: Key, value: Value): Option[Value] ={
val previous = get(key)
set(key, value)
previous
}
def invalidate(key: Key): Value
protected def default(key: Key): Value
def apply(key: Key) = get(key) orElse default(key)
def toString() = "Cache(%s)" format this
}
trait Memoize[T,R](f: T => R, cache: Cache[T,R]) extends (T => R){
def apply(arg: T) = cache get (arg) getOrElse (cache set (arg, f(arg)))
def toString() = "<memoize>"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment