Lazily评估索引序列类型 [英] Lazily evaluated indexed sequence type

查看:215
本文介绍了Lazily评估索引序列类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要构建从外部资源加载的对象序列。这种昂贵的操作的加载需要被延迟,直到需要对象的时间。在构建集合之后,我需要对包含的对象的索引访问。 Scala标准库是否提供适合此用例的集合?

I need to build a sequence of objects that are loaded from an external resource. This loading being an expensive operation needs to be delayed until the time the objects are needed. After the collection is built, I need an indexed access to the contained objects. Does Scala standard library provide a collection suited to this use case? If not, what will be the best way to implement it?

编辑

索引查找最好是


The indexed lookup should preferably be an O(1) operation.

推荐答案

Strange,Miles最近发送了推文。然后,回复会指出需要 在的名称.scala在scalaz和另一个指向 LazyParameter 。

Strange, Miles recently tweeted about this. A reply then points out to Need at the end of Name.scala in scalaz and another one points to specs' LazyParameter.

需要少许测试:

import scalaz._
import Scalaz._
val longOp = { var x = 0; () => {println("longOp"); x += 1; x }}
val seq = Seq(Need(longOp()), Need(longOp()))
val sum = seq.map(_.value).sum
val sum = seq.map(_.value).sum

val v = Need(longOp())
val s = v.map("got " + _)
println(s.value)
println(s.value)

列印:

longOp: () => Int = <function0>
seq: Seq[scalaz.Name[Int]] = List(
  scalaz.Name$$anon$2@1066d88, scalaz.Name$$anon$2@1011f1f)
longOp
longOp
sum: Int = 3
sum: Int = 3
v: scalaz.Name[Int] = scalaz.Name$$anon$2@133ef6a
s: scalaz.Name[java.lang.String] = scalaz.Name$$anon$2@11696ec
longOp
got 3
got 3

所以 longOp 在第一次访问值时才调用一次。

So longOp is only called once on first access of value.

这篇关于Lazily评估索引序列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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