[英]Is it a library bug in a functional language when a function with the same name but for different collections produces different side effects?
我正在使用 Scala 2.13.1 并在工作表中评估我的示例。
首先,我定义了两个函数,它们将a到 ( z -1) 的范围返回为 stream 或惰性列表。
def streamRange(a: Int, z: Int): Stream[Int] = {
print(a + " ")
if (a >= z) Stream.empty else a #:: streamRange(a + 1, z)
}
def lazyListRange(a: Int, z: Int): LazyList[Int] = {
print(a + " ")
if (a >= z) LazyList.empty else a #:: lazyListRange(a + 1, z)
}
然后我调用这两个函数,获取 3 个元素的 Stream/LazyList 并将它们转换为 List:
streamRange(1, 10).take(3).toList // prints 1 2 3
lazyListRange(1, 10).take(3).toList // prints 1 2 3 4
在这里,我再次做同样的事情:
val stream1 = streamRange(1, 10) // prints 1
val stream2 = stream1.take(3)
stream2.toList // prints 2 3
val lazyList1 = lazyListRange(1,10) // prints 1
val lazyList2 = lazyList1.take(3)
lazyList2.toList // prints 2 3 4
打印 1 是因为访问了 function 并且打印语句在开头。 没有惊喜。
但我不明白为什么为惰性列表打印额外的 4 而不是为 stream 打印。
My assumption is that at the point where 3 is to be concatenated with the next function call, the LazyList version visits the function, whereas in the Stream version the function is not visited. 否则 4 将不会被打印。
这似乎是无意的行为,至少是出乎意料的。 但是,这种副作用的差异是否会被视为错误,或者只是 Stream 和 LazyList 评估中的详细差异。
Stream
使用Deferer
实现#::
implicit def toDeferrer[A](l: => Stream[A]): Deferrer[A] = new Deferrer[A](() => l)
final class Deferrer[A] private[Stream] (private val l: () => Stream[A]) extends AnyVal {
/** Construct a Stream consisting of a given first element followed by elements
* from another Stream.
*/
def #:: [B >: A](elem: B): Stream[B] = new Cons(elem, l())
/** Construct a Stream consisting of the concatenation of the given Stream and
* another Stream.
*/
def #:::[B >: A](prefix: Stream[B]): Stream[B] = prefix lazyAppendedAll l()
}
Cons
:
final class Cons[A](override val head: A, tl: => Stream[A]) extends Stream[A] {
而LazyList
Deferer
#::
:
implicit def toDeferrer[A](l: => LazyList[A]): Deferrer[A] = new Deferrer[A](() => l)
final class Deferrer[A] private[LazyList] (private val l: () => LazyList[A]) extends AnyVal {
/** Construct a LazyList consisting of a given first element followed by elements
* from another LazyList.
*/
def #:: [B >: A](elem: => B): LazyList[B] = newLL(sCons(elem, l()))
/** Construct a LazyList consisting of the concatenation of the given LazyList and
* another LazyList.
*/
def #:::[B >: A](prefix: LazyList[B]): LazyList[B] = prefix lazyAppendedAll l()
}
其中sCons
:
@inline private def sCons[A](hd: A, tl: LazyList[A]): State[A] = new State.Cons[A](hd, tl)
和Cons
:
final class Cons[A](val head: A, val tail: LazyList[A]) extends State[A]
这意味着在定义级别上:
Steam
懒洋洋地评价它尾巴的创作LazyList
懒惰地评估其尾部的内容其他副作用之间的差异是显而易见的......如果这些都不是。
如果您想处理可能无限的重要计算序列,请使用适当的流库:Akka Streams、FS2、ZIO Streams。 内置流/惰性列表是为纯计算而制作的,如果您进入不纯目录,您应该假设不提供有关副作用的保证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.