有“懒人地图"吗? [英] Is there a 'lazy map'?

查看:31
本文介绍了有“懒人地图"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像Stream是一个懒惰的Seq,有没有Map的懒惰版本?

Just like Stream is a lazy Seq, is there a lazy version of Map?

我想做什么:

val lm = LazyMap[Int, String]((a) => {
  println("only once")
  (a * a).toString()
})
lm.get(10) // print "only once"
lm.get(10) // print nothing

推荐答案

您基本上是在要求缓存.您可能会尝试使用 scalaz.Memo,它为给定的函数添加了记忆功能.请参阅 http://eed3si9n.com/learning-scalaz/Memo.html

You are basically asking for a cache. You might have a shot at using scalaz.Memo, which adds memoization to a given function. See http://eed3si9n.com/learning-scalaz/Memo.html

这将给出类似:

val lm: Int => String = Memo.mutableHashMapMemo[Int, String] { a =>
  println("only once")
  (a * a).toString()
}

但是请注意,您得到的是函数,而不是地图.这意味着您无法测试给定密钥是否存在,您只能申请.但如果我相信你的例子,在你的情况下,这正是你想要的.

Note however that what you get is a function, not a map. This means that you cannot test for the presence or absence of a given key, you can only apply. But if I am to trust your example, in your case this is exactly what you want.

这篇关于有“懒人地图"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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