Created
June 30, 2010 11:53
-
-
Save retronym/458558 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
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) | |
} | |
} |
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
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) | |
} | |
} |
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
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