gpt4 book ai didi

scala - Scala 可变集合的 View 有什么惰性?

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

我认为这个问题本质上是关于可变性背景下的懒惰是什么。

Programming in Scala(或 the docs)中,他们给出了如何在不可变和可变集合上使用 View 的示例。在那个部分,他们说

[transformer methods] take at least one collection as their receiver object and produce another collection in their result. ... A view is a special kind of collection that represents some base collection, but implements all of its transformers lazily.

他们给出了不可变集合的示例,我理解懒惰在那里是如何工作的。但是我正在努力解决惰性在可变集合示例中所扮演的角色:

Many transformer functions on [views over mutable sequences] provide a window into the original sequence ... an example ...

val arr = (0 to 9).toArray
val subarr = arr.view.slice(3, 6)

The view does not copy these elements, it just provides a reference to them.

def negate(xs: collection.mutable.Seq[Int]) = 
for (i <- 0 until xs.length) xs(i) = - xs(i)

negate(subarr)
arr // Array(0, 1, 2, -3, -4, -5, 6, 7, 8, 9)

我明白为什么我们会得到那个答案。但是转换器 slice 有什么懒惰的地方呢?我将惰性理解为仅在需要时才计算值(就像不可变集合示例一样)。但是 slice 中的值永远不会被计算,它们只是对 arr 中的值的引用,即使在调用 negate 之后也是如此。这是我对懒惰的误解吗?或者文档是否以另一种方式使用惰性?还是别的?

最佳答案

下面是这种懒惰行为的一个更好的例子:

val a = Array(1,2,3)
val b = a.map(_ + 5)
val c = a.view.map(_ + 5)
println(b(1)) //prints 7
println(c(1)) // prints 7

a(1) = 5

println(b(1)) // still prints 7, since that array was computed on instantiation
println(c(1)) // now prints 10, since elements of c are lazily evaluated each time.

关于scala - Scala 可变集合的 View 有什么惰性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56316868/

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