gpt4 book ai didi

arrays - 是否有可能有一个懒惰地评估其元素的数组?

转载 作者:行者123 更新时间:2023-12-04 14:51:03 24 4
gpt4 key购买 nike

考虑这个 BigInt 类,它应该缓存 smallValues 中的一些常见值。 :

object BigInt {
lazy val smallValues = Array(Zero, One, Two)
lazy val Zero = new BigInt(0, Array[Long]())
lazy val One = new BigInt(1, Array[Long](1))
lazy val Two = new BigInt(1, Array[Long](2))

private lazy val cacheSize = smallValues.length


def apply(num: Long): BigInt = {
// Is the number cached?
if (0 <= num && num < cacheSize) smallValues(num.toInt)
// Figure out the sign and make the number positive after that
else {
val (sign, value) = if (num < 0) (-1, num * -1) else (1, num)
new BigInt(sign, Array(value))
}
}
}

class BigInt private(val sign: Int, val num: Array[Long]) extends Ordered[BigInt] {
println("Constructing BigInt")
...
}

这里的问题是访问数组的一个元素会强制评估所有元素:
scala> BigInt.smallValues(0)
Constructing BigInt
Constructing BigInt
Constructing BigInt
res0: BigInt = BigInt@2c176570

我怎么能解决这个问题?

编辑:看着提议的解决方案,我真的很想知道在没有进一步复杂化的情况下分配它们是否会更有效。你怎么认为?

最佳答案

编辑我的答案,因为我认为这是一个关于你想做的事情的玩具例子,而且你的真实物体 build 起来非常昂贵,懒惰给你买了一些东西。如果问题显示出更像真实代码的东西,那么懒惰就没有意义了。惰性对象比严格对象更大,创建成本更高。尽管如此,我仍然保留以下代码,因为它确实显示了如何创建一个惰性包装器并且它确实“工作”(从功能上正确的意义上说),即使它在良好的意义上不“工作”您的用例的想法。

class Lazy[T] (expr : => T) {lazy val ! = expr}
object Lazy{def apply[T](expr : => T) = new Lazy({expr})}

class BigInt (val sign: Int, val num: Array[Long]) {
println("Constructing BigInt")
}

object BigInt {
val smallValues = Array(
Lazy(new BigInt(0, Array[Long]())),
Lazy(new BigInt(1, Array[Long](1))),
Lazy(new BigInt(1, Array[Long](2)))
)

private val cacheSize = smallValues.length.toLong

def apply(num: Long): BigInt = {
// Is the number cached?
if (0 <= num && num < cacheSize) smallValues(num.toInt)!
// Figure out the sign and make the number positive after that
else {
val (sign, value) = if (num < 0) (-1, num * -1) else (1, num)
new BigInt(sign, Array(value))
}
}
}


scala> BigInt(1)
Constructing BigInt
res0: BigInt = BigInt@c0dd841

scala> BigInt(1)
res1: BigInt = BigInt@c0dd841

scala> BigInt(2)
Constructing BigInt
res2: BigInt = BigInt@4a6a00ca

scala> BigInt(2)
res3: BigInt = BigInt@4a6a00ca

关于arrays - 是否有可能有一个懒惰地评估其元素的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6551372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com