簡體   English   中英

Scala-惰性評估說明

[英]Scala - lazy evaluation explanation

歡迎,

誰能告訴我為什么我的代碼沒有按我預期的方式工作? 我有以下測試代碼段:

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)
}

也許有人可以解釋我為什么會這樣,因為我無法調試問題?

可以這么說:流是惰性的-僅按需求進行評估(因為按名稱參數進行調用)。

采用:

Stream(1).take(2).toList

強制評估

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM