拉皮条 scalaz 备忘录 [英] Pimping scalaz Memo

查看:111
本文介绍了拉皮条 scalaz 备忘录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢新的 scalaz Memo 功能,但发现它缺少两件事:1) 它隐藏了我需要访问的底层 Map——至少是所有值的列表,以及 2) 我想要一个已实现的版本使用 val scala.collection.concurrent.TrieMap,我在某处读到它比 var Map 更可取.

I like the new scalaz Memo functionality but find it lacks 2 things: 1) it hides the underlying Map, which I need access to--at least a List of all the values, and 2) I want a version that's implemented using a val scala.collection.concurrent.TrieMap, which I read somewhere is preferable than a var Map.

我还不是一个隐含的巫师.有没有办法拉皮条这个 Memo 类来添加支持此功能的版本,或者我将不得不剪切/粘贴到一个独特的新类中?

I'm not yet an implicit wizard. Is there a way to pimp this Memo class to add versions that support this capability or am I going to have to cut/paste into a distinct, new class?

推荐答案

这可以通过内置的 Memo.memo 函数来完成.Memo.memo 从函数 F => K => V 创建一个 Memo 实例.这也让您可以轻松访问底层特里.例如:

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)

这篇关于拉皮条 scalaz 备忘录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆