欢迎,
任何人都可以告诉我为什么我的代码没有按照我的预期行事吗?我有以下测试片段:
sealed trait Stream[+A] {
import Stream._
// may cause stackOverflow for large streams
def toList: List[A] = this match {
case Empty => Nil
case Cons(h, t) => h() :: t().toList
}
def toList2: List[A] = {
// stackOverflow secure solution
def iterate(s: Stream[A], acc: List[A]): List[A] = s match {
case Empty => acc
case Cons(h, t) => iterate(t(), h() :: acc)
}
iterate(this, List()).reverse
}
def take(n: Int): Stream[A] = (n, this) match {
case (v, Empty) if v > 0 => throw new IllegalStateException()
case (0, _) => empty()
case (v, Cons(h, t)) => cons(h(), t().take(n - 1))
}
def drop(n: Int): Stream[A] = (n, this) match {
case (v, Empty) if v > 0 => throw new IllegalStateException()
case (0, _) => this
case (_, Cons(h, t)) => t().drop(n - 1)
}
}
case object Empty extends Stream[Nothing]
case class Cons[+A](h: () => A, tl: () => Stream[A]) extends Stream[A]
object Stream {
def cons[A](h: => A, tl: => Stream[A]): Stream[A] = {
lazy val head = h
lazy val tail = tl
Cons(() => head, () => tail)
}
def empty[A]():Stream[A] = Empty
def apply[A](as: A*): Stream[A] = if (as.isEmpty) empty() else cons(as.head, apply(as.tail: _*))
}
问题是,以下测试失败(它不会抛出异常):
an [IllegalStateException] shouldBe thrownBy {
Stream(1).take(2)
}
也许任何人都可以解释为什么会发生这种情况,因为我无法调试问题?
答案 0 :(得分:0)
你说的是:流是懒惰的 - 只按需求评估(因为通过名称参数调用)。
使用:
Stream(1).take(2).toList
强制评估