问题描述
我有一个对象集合
case class Record(value: Whatever)
val list: List[Record]
并希望选择排名最高的
list.foldLeft(list.head) { (best, current) =>
if (rank(current.value) > rank(best.value)) {
current
} else {
best
}
}
让我们假设rank
是昂贵的,最好不要在同一对象上两次被调用.我有什么选择?
Let's suppose that rank
is expensive and better not be called twice on the same object. What are my options?
我可以折叠成元组(rank, record)
,但这可能意味着在迭代过程中创建辅助对象.我应该担心开销吗?或者更确切地说
I can fold to tuple (rank, record)
but this probably means creating auxiliary objects during iteration. Should I worry about the overhead? Or rather
-
如何在Scala中有效地实现这一点?
How can this be implemented efficiently in Scala?
对问题的正确的功能性"观点是什么?
What's the proper 'functional' view of the problem?
推荐答案
如果您不可避免地要对同一对象重复进行昂贵的计算,则可以尝试使用记忆.
If you're in a situation where repeating expensive calculations on the same objects appears unavoidable, you might try memoization.
// memoize this function (arity 1)
def memo[A,R](f :A => R): A => R =
new collection.mutable.WeakHashMap[A,R] {
override def apply(a: A) = getOrElseUpdate(a,f(a))
}
// rankM is a memoized Record => Rank function
val rankM = memo{ r:Record => rank(r.value) }
有时,当您希望Map
在内存受挑战的环境中忘记"很少访问的键时,会使用WeakHashMap
.
A WeakHashMap
is used sometimes when you want the Map
to "forget" seldom accessed keys in a memory-challenged environment.
这篇关于折叠时的中间值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!