Pimping scalaz Memo

假如想象 提交于 2019-12-04 19:22:46

This can be accomplished with the built-in Memo.memo function. Memo.memo creates a Memo instance from a function F => K => V. This also lets you get access to the underlying trie easily. For example:

scala> def trieMemo[A, B](trie: collection.concurrent.TrieMap[A, B]) = 
         Memo.memo[A, B](f => k => trie.getOrElseUpdate(k, f(k)))
trieMemo: [A, B](trie: scala.collection.concurrent.TrieMap[A,B])scalaz.Memo[A,B]

scala> val trie = collection.concurrent.TrieMap[Int, Int]()
trie: scala.collection.concurrent.TrieMap[Int,Int] = TrieMap()

scala> val f = trieMemo(trie)(n => n * n)
f: Int => Int = <function1>

scala> f(5)
res0: Int = 25

scala> f(10)
res1: Int = 100

scala> trie
res2: scala.collection.concurrent.TrieMap[Int,Int] = TrieMap(5 -> 25, 10 -> 100)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!