Skip to content

Instantly share code, notes, and snippets.

@retronym
Created June 30, 2010 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save retronym/458558 to your computer and use it in GitHub Desktop.
Save retronym/458558 to your computer and use it in GitHub Desktop.
package example
import com.google.common.base.Function
import com.google.common.collect.MapMaker
object MemoUtil {
import scalaz._
import Scalaz._
/**
* A caching wrapper for a function (K => V), backed by a ConcurrentHashMap from Google Collections.
*/
def concurrentHashMapMemo[K, V]: Memo[K, V] = {
memo[K, V] {(f: (K => V)) =>
val map: java.util.concurrent.ConcurrentMap[K, V] = new MapMaker().makeComputingMap(f)
(k: K) => map.get(k)
}
}
implicit def ScalaFunctionToGoogleFuntion[T, R](f: T => R): Function[T, R] = new Function[T, R] {
def apply(p1: T) = f(p1)
}
}
package scalaz
sealed trait Memo[K, V] {
def apply(z: K => V): K => V
}
trait Memos {
def memo[K, V](f: (K => V) => K => V): Memo[K, V] = new Memo[K, V] {
def apply(z: K => V) = f(z)
}
}
import example.MemoUtil._
trait A
trait B
trait Z
val memo: Memo[(A, B), Z] = concurrentHashMapMemo
def expensiveFunction(a: A, b: B): Z = //...
val expensiveFunctionMemoized: ( (A, B) ) => Z = memo { case (a, b) => expensiveFunction(a, b) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment