gpt4 book ai didi

scala - lazyMap其实不懒惰?

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

这是阶梯书中的一个例子:

object Example1 {
def lazyMap[T, U](coll: Iterable[T], f: T => U) = {
new Iterable[U] {
def iterator = coll.iterator.map(f)
}
}
val v = lazyMap[Int, Int](Vector(1, 2, 3, 4), x => {
println("Run!")
x * 2
})
}

控制台结果:

Run!
Run!
Run!
Run!
v: Iterable[Int] = (2, 4, 6, 8)

怎么这么懒?

最佳答案

它调用 map 函数的原因是因为您在调用 lazyMap 上的 toString 函数的 Scala 控制台中运行。如果您通过在代码末尾添加 "" 确保不返回该值,它将不会映射:

scala> def lazyMap[T, U](coll: Iterable[T], f: T => U) = {
new Iterable[U] {
def iterator = coll.iterator.map(f)
}
}
lazyMap: [T, U](coll: Iterable[T], f: T => U)Iterable[U]

scala> lazyMap[Int, Int](Vector(1, 2, 3, 4), x => {
println("Run!")
x * 2
}); ""
res8: String = ""

scala>

关于scala - lazyMap其实不懒惰?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33187567/

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